我正在尝试找出一种在使用JavaScript的reduce函数时有条件地中断迭代的方法。给定以下代码对整数数组求和并将返回数字10:[0,1,2,3,4].reduce(function(previousValue,currentValue,currentIndex,array){returnpreviousValue+currentValue;});我怎样才能做这样的事情:[0,1,2,3,4].reduce(function(previousValue,currentValue,currentIndex,array){if(currentValue==="WHATEVER"){//
我很好奇为什么在数组上使用.reduce时previousValue在以下代码中总是未定义:代码:[2,2,2,3,4].reduce(function(previousValue,currentValue){console.log("PreviousValue:"+previousValue);console.log("CurrentValue:"+currentValue);},0)输出:PreviousValue:0(index):CurrentValue:2(index):PreviousValue:undefined(index):CurrentValue:2(index):