我试图理解此代码。 Array(8).fill(0).map(Number.call, Number)
。问题在于,这种行为很难理解,因为无法看到数字的实现。如果尝试使用.toString Number,它将仅显示“本机代码”。将绑定和调用与内置函数一起使用时也是如此。我如何找出这种行为?
答案 0 :(得分:2)
如果您想详细了解Number
的工作原理,请查看其ECMAScript specs。
如果您想了解Number
的总体工作原理,请查看其MDN documentation。
基本上,Number(value)
所做的只是将value
转换为数字类型。没什么。
我相信您需要了解的内容实际上是关于Function.prototype.call
而不是Number
。
当我们将上面的代码转换成花哨的代码时,我们大致得到了这样的东西(这对于下面的解释很重要):
console.log(
Array(8).fill(0).map(Function.prototype.call, Number)
);
现在,在.map
中,它收到2个参数:
currentValue
,currentIndex
,originalArray
。this
值因此,上面的代码所做的是传递Number.call
作为回调,并传递Number
作为自定义此值。
如果您了解.call
方法,您将知道它必须至少接收1个参数:
this
值。了解了所有这些信息之后,我们现在可以将上面的代码转换为更精美的代码:
console.log(
Array(8).fill(0).map(function(currentValue, currentIndex, originalArray){
return this.call(currentValue, currentIndex);
}, Number)
);
这也可以翻译成花哨的东西:
console.log(
// Making `currentValue` into `_` because its existence does not matter in this case
Array(8).fill(0).map(function(_, currentIndex){
return Number.call(_, currentIndex);
})
);
现在,这是最容易理解的最终翻译:
console.log(
Array(8).fill(0).map((_, i) => Number(i))
);