首先我们看一下reduce function的定义
它接受一个有四个参数的函数
Array.prototype.reduce((accumulator, currentValue, currentIndex, array) => {
// the function must return a value.
// accumulator: the accumulator accumulates the return value.
// currentValue: The current element being processed in the array.
// currentIndex: The index of the current element being processed in the array. Starts at index 0 if an initialValue is provided and at index 1 otherwise.
// array: The array reduce() was called upon.
}, initialValue);
如果您不提供初始值,则累加器将是数组中的第一个元素,而 currentValue 将是数组中的第二个元素
现在第一次运行函数时它会返回 1,因为只有两个值需要检查
翻译成这个
// a = accumulator = {id:0, x:20, y:20}
// b = currentValue= {id:1, x:50, y:50}
Math.max(a.id, b.id)
这很好,但是当有更多这种情况发生时
第一个周期
// a = accumulator = {id:0, x:20, y:20}
// b = currentValue= {id:1, x:50, y:50}
Math.max(a.id, b.id) // return 1
第二周期
// a = accumulator = 1 returned from the first cycle
// b = currentValue= {id:2, x:20, y:20}
Math.max(a.id, b.id) // returns NaN because 1.id doesn't makes sense
解决方案
let localNodes = [
{id:0, x:20, y:20},
{id:1, x:50, y:50}
]
function addNode(node){
let maxId = localNodes.reduce( (accumulator, currentValue) => {
/*
here we gonna start with 0 which means the accumulator
will equal 0 at the first cycle and the currentValue
will be the first element in the array
*/
Math.max(accumulator,currentValue.id)
},0);
maxId++
localNodes.push({id:maxId, x:node.x, y:node.y})
}
addNode({x:20, y:20})
addNode({x:20, y:20})
addNode({x:20, y:20})
console.log(localNodes)
.as-console-wrapper {
max-height: 100% !important;
}