# JavaScript“new Array（n）”和“Array.prototype.map”古怪

``````let arr = new Array(10).map((val,idx) => idx);
``````

``````[0,1,2,3,4,5,6,7,8,9]
``````

``````let arr = new Array(10).fill(undefined).map((val,idx) => idx);
``````

``console.log(new Array(10).fill(undefined).map((val, idx) => idx));``

``````let arr = Array.apply(null, Array(10)).map((val, idx) => idx);
``````

``console.log(Array.apply(null, Array(10)).map((val, idx) => idx));``

Question

``````    >>> x = new Array(3)
[undefined, undefined, undefined]
>>> y = [undefined, undefined, undefined]
[undefined, undefined, undefined]

>>> x.constructor == y.constructor
true

>>> x.map(function(){ return 0; })
[undefined, undefined, undefined]
>>> y.map(function(){ return 0; })
[0, 0, 0]
``````

`Array(3)`大致產生`{length: 3}`

`[undefined, undefined, undefined]`創建編號的屬性：
`{0: undefined, 1: undefined, 2: undefined, length: 3}`

map（）實現僅對已定義的屬性起作用。

``````>>> x = new Array(3)
[]
>>> x.length
3
``````

`map`的MDC頁面：

[...] `callback`僅針對已賦值的數組的索引; [...]

`[undefined]`實際上將setter應用於索引（es），以便`map`將迭代，而`new Array(1)`僅使用`undefined`的默認值初始化索引（es），以便`map`跳過它。