Array.apply
的第二个参数需要一个数组(-like)值.然后,它将为这个类似数组的对象中的每个插槽创建一个参数.
由于此代码将{ length: 5 }
作为参数传递,apply
方法将使用5个值调用Array
.但是当在0范围内为i
读取{ length: 5 }[i]
时..4.undefined
.所以Array.apply(null, { length: 5 })
将转化为Array(undefined, undefined, undefined, undefined, undefined)
.
然后,.map
调用有第二个参数,即thisArg
参数.这确保不仅调用call
,而且调用Number.call
,即使用正确的this
设置.对于Number.call
,第一个参数将接收这undefined
个值(在上一段中解释),并作为second个参数,映射的索引.所以我们接到这些电话:
Number.call(undefined, 0)
Number.call(undefined, 1)
Number.call(undefined, 2)
Number.call(undefined, 3)
Number.call(undefined, 4)
这与以下结果相同:
Number(0)
Number(1)
Number(2)
Number(3)
Number(4)
.map
将返回一个包含这些值的array.
更新的方法
自ECMAScript 2015以来,JavaScript拥有Array.keys()
种数组文字的扩展语法.因此,我们现在可以以一种不那么神秘的方式实现同样的目标:
console.log([...Array(5).keys()]);