我通过MDN文档(链接(阅读了有关javascript reduce函数的内容。但是我不能够理解其中的一段代码。
这是代码(链接(:
if (!Array.prototype.mapUsingReduce) {
Array.prototype.mapUsingReduce = function(callback, initialValue) {
return this.reduce(function(mappedArray, currentValue, index, array) {
mappedArray[index] = callback.call(initialValue, currentValue, index, array)
return mappedArray
}, [])
}
}
[1, 2, , 3].mapUsingReduce(
(currentValue, index, array) => currentValue + index + array.length
)
我的主要问题是:在上面的代码中,initialValue参数的用途是什么?为什么它调用initialValue为this
的回调(因为call
的第一个参数应该是this
(,即使callback(currentValue, index, array)
工作正常。此外,if语句if (!Array.prototype.mapUsingReduce)
是否必要?
大多数Array.prototype
方法都带有一个可选的附加参数以及一个名为thisArg
的回调函数。它是在执行回调时用作this
的值。initialValue
是一个不好的参数名称,尤其是在reduce
的上下文中。它可能与reduce
的initialValue
参数混淆
在您的情况下,这并不重要,因为您正在使用箭头函数作为回调。无法设置this
值。如果你有一个普通的function(){}
,你可以使用其中的this
在第一个示例中,Set
对象被用作thisArg
。在回调中,根据添加currentValue
时Set
的大小是否保持不变,检查currentValue
是否重复。
第二个示例使用具有sum
的对象来跟踪数组的累积和。
Array.prototype.mapUsingReduce = function(callback, thisArg) {
return this.reduce(function(mappedArray, currentValue, index, array) {
mappedArray[index] = callback.call(thisArg, currentValue, index, array)
return mappedArray
}, [])
}
const repeatStatus = [1, 2, 2, 3].mapUsingReduce(function(currentValue) {
return this.size === this.add(currentValue).size ? 'duplicate' : 'unique'
}, new Set()) // <-- this object is the "thisArg"
console.log(...repeatStatus)
const cumulativeSum = [1, 2, 3, 4, 5].mapUsingReduce(function(currentValue) {
return this.sum += currentValue
}, { sum: 0 })
console.log(...cumulativeSum)
用于确保该方法只创建一次而不会一次又一次地重写的条件if (!Array.prototype.mapUsingReduce)
。
示例应将initialValue
替换为thisArg
(或_this,即..(。命名错误。
使用call()
,您可以在回调中使用this
上下文。这不是必需的。
此外,使用if (!Array.prototype.mapUsingReduce)
,您可以安全地执行上述代码两次。这也不是必须的。