🍄sparse array
JS ⟩ object ⟩ built-in ⟩ Array ⟩ sparse array
array that has "holes" in it.
"holes" are (usually) treated as undefined.
loops and array methods treat "holes" in sparse arrays differently.
forEach:ignores "holes".
map :preserves holes.
filter :ignores holes.
if an array literal contains multiple commas in a row, with no value between, the array is sparse.
array literal syntax allows an optional trailing comma, so
[,,]
has a length of 2, not 3❗
Array(n) vs. Array(n).fill()
Array(3)
只會設定陣列長度
{length: 3}
,並不會設定「整數索引」屬性如果做
.map()
,只會得到空陣列,因為.map()
會保留「洞」。
Array(3).fill()
會填入
undefined
,並設定「整數索引」屬性,這時使用.map()
就會有實際效果。
Last updated