📍Array(n) vs. Array(n).fill()
Array(3)
只會設定陣列長度
{length: 3},並不會設定「整數索引」屬性如果做
.map(),只會得到空陣列,因為.map()會保留「洞」。 ( 👉 下面程式第 15 行 )
Array(3).fill()
會填入
undefined,並設定「整數索引」屬性,這時使用.map()就會有實際效果。( 👉 下面程式第 19 行 )
const { log } = console;
let n = 3;
// ⭐️ Array(n) does NOT set integer properties❗️
let emptyArray = Array(n); // only set {length: n}
log(Object.keys(emptyArray)); // []
// ⭐️ Array(n).fill() DOES set integer properties❗️
let filledArray = Array(n).fill(); // {0:undefined, 1:undefined, ...}
log(Object.keys(filledArray)); // [ '0', '1', '2' ]
// ⭐ map over INTEGER properties❗️️ (⭐️ no integer to map over)
let a1 = emptyArray.map((_, i) => i); // [ <3 empty items> ]
log(a1, a1.length); // ⭐️ `length` is kept by map
// ⭐ map over INTEGER properties❗
let a2 = filledArray.map((_, i) => i); // [ 0, 1, 2 ]
log(a2);array.fill() - 沒填寫參數,表示 filled with
undefined
🌀 Array.matrixFill() - fill a matrix.
Last updated
Was this helpful?