我试图理解这段代码。 Array(8).fill(0).map(Number.call, Number)
。问题是这种行为很难理解,因为无法看到 number 的实现。如果您尝试 .toString Number 它只会显示“ native 代码”。对于使用内置函数进行绑定(bind)和调用也是如此。我怎样才能知道它应该如何表现?
最佳答案
如果您想了解 Number
的详细工作原理,请查看其 ECMAScript specs .
如果您想了解 Number
一般如何工作,请查看其 MDN documentation .
基本上,Number(value)
所做的就是将 value
转换为数字类型。没有别的了。
我相信你需要理解才能理解这段代码实际上是关于Function.prototype.call
而不是数字
。
当我们将上面的代码翻译成不太花哨的代码时,我们得到大致如下的代码(这对于下面的解释很重要):
console.log(
Array(8).fill(0).map(Function.prototype.call, Number)
);
现在,在 .map
,它接收 2 个参数:
- 回调,有 3 个参数:
currentValue
、currentIndex
、originalArray
。 - 自定义
此
值
所以上面的代码所做的就是传递 Number.call
作为回调,并传递 Number
作为自定义 this 值。
如果您了解 .call
方法,您就会知道它必须至少接收 1 个参数:
这个
值。- ...参数n
了解了所有这些,我们现在可以将上面的代码转换为更不花哨的代码:
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))
);
关于javascript - 如何找出 javascript 内置函数上的调用和绑定(bind)行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63947985/