Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

# js - 動態產生 0-N 的陣列 #78

Open
NaClYen opened this issue Aug 12, 2021 · 0 comments
Open

# js - 動態產生 0-N 的陣列 #78

NaClYen opened this issue Aug 12, 2021 · 0 comments

Comments

@NaClYen
Copy link
Owner

NaClYen commented Aug 12, 2021

忘了三次, 該紀錄一下XD

code

function createArray1(length) {
  const arr = [];
  for (let i = 0; i < length; i += 1) arr.push(i);
  return arr;
}

function createArray2(length) {
  return Array(length)
    .fill(0)
    .map((_, index) => index);
}

function createArray3(length) {
  return Array.from({ length }, (_, index) => index);
}

function createArray4(length) {
  return [...Array(length).keys()];
}

相容性

雖然現在已經普遍使用 Polyfill, 但還是列一下版本需求

function version
Array.from ES2015
Array.prototype.fill ES2015

陣列中的空缺欄位(empty)不會被迭代(iterator)

平常默默地在利用這機制, 太自然反而沒意識到XDD

// 其中 2 & 5 中間那格就是所謂的空缺欄位
let a = [1, 2, , 5]

a.forEach(console.log)
// output
// 1 1 0 (4) [1, 2, empty, 5]
// 1 2 1 (4) [1, 2, empty, 5]
// 1 5 3 (4) [1, 2, empty, 5]

因此, 如果你這樣寫不會得到期望的結果:

Array(5).map((_, index) => index)
// [ empty, empty, empty, empty, empty ]
// map 實際上沒有跑任何內容

參考

tags: js ts javascript typescript array
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant