console.log(
Array.from({ length: 3 }, Function.call, Number)
);
根据我的理解,上面的代码将(value, index)
传递给Function
原型(prototype)的.call
方法。
并且 .call
的 this
值设置为 Number
。
所以它完全一样:
Array.from({ length: 3 }, (value, index) => Number.call(value, index))
在 VSCode 中,我的工具提示将函数描述为:
mapfn: (v: any, k: number) => any
这就是我得到 (value, index)
的地方,假设 k
表示 key
/index
。
但是 Number
只接受一个数字参数。所以它将接受value
,并忽略index
。
但是value
是undefined
,因为数组还没有初始化。
那么代码如何生成一个数组,其中每个值都等于其索引,而不是充满 NaN
?
最佳答案
.call
接受的第一个参数是要调用的函数的 this
值。其余参数是函数调用时使用的普通参数。所以,这:
Number.call(value, index)
相当于:
Number(index)
Number
中的 this
值设置为 value
。
value
确实是未定义的,但是 Number 构造函数不关心它的调用上下文,它的 this
,所以它实际上被忽略并从索引。
这是另一种看待它的方式:下面是一个名为 foo
的函数,当 .call
ed 时,它不关心第一个参数,只接受考虑到第二个:
function foo(arg) {
return 'foo' + arg;
}
console.log(
foo.call('IGNORED PARAMETER', 'bar')
);
关于javascript - 这个数组初始化速记是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63948662/