🍄sparse array

JSobjectbuilt-inArray ⟩ sparse array

  • array that has "holes" in it.

  • "holes" are (usually) treated as undefined.

loops and array methods treat "holes" in sparse arrays differently.

  • for-oftreats "holes" as undefined.

  • forEachignores "holes".

  • mappreserves holes.

  • filterignores holes.

👉 how array methods deal with "holes" ?

deleting an array element leaves a “hole” in the array and does not change the array’s length (sparse array)

Array(n) vs. Array(n).fill()

Array(3)

  • 只會設定陣列長度 {length: 3},並不會設定整數索引屬性

  • 如果做 .map(),只會得到空陣列,因為 .map() 會保留「洞」。

Array(3).fill()

  • 會填入 undefined,並設定整數索引」屬性,這時使用 .map() 就會有實際效果。

Last updated