我有一个像这样的数组:
<label><input type="checkbox" onclick="checkall(this)">Check all</label>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
还有一个reduce函数:
let oddsArray = [undefined, undefined, 5, 5]
当我调用console.log时,我得到了:
const reducer = (accumulator, currentValue) => accumulator + currentValue
直到数组不再包含undefined为止:
console.log(oddsArray.reduce(reducer, 1), 'oddsArray') /// NAN
我希望能够将数组中的所有数字加起来,即使该数组中包含未定义的值也是如此。因此初始数组应等于:
[5, 5, 5, 5] /// 20
我该如何实现?
谢谢!
答案 0 :(得分:4)
您可以检查undefined
的值,如下所示:currentValue || 0
let oddsArray = [undefined, undefined, 5, 5]
const reducer = oddsArray.reduce((accumulator, currentValue) =>
accumulator + (currentValue || 0), 0);
console.log(reducer);
答案 1 :(得分:1)
如果您需要更通用的方法,即仅对具有多种元素类型的数组中的数字求和,则可以使用Number.isNaN()来检查reducer
的当前值是否为数字:
let oddsArray = [undefined, undefined, 5, 5, null, "hola", {"foo":"bar"}];
const reducer = (acc, currVal) => acc + (isNaN(currVal) ? 0 : currVal);
let res = oddsArray.reduce(reducer, 0);
console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}