-1 javascript arrays reduce sum ecmascript-6
我只需要将这个数组的数字求和,reduce但是我不知道怎么做。
这是我的代码和尝试:
let arr = [1,2,3,4,6,true,"Dio Brando", false,10,"yare yare"];
let sum = arr.reduce((a.b)=> typeOf.a =="number" && typeOf.b =="number"? a+b :false)
console.log(sum);
Run Code Online (Sandbox Code Playgroud)
您需要进行以下更改:
我用一些更有用的变量名重写了代码,以解释reduce中发生的事情。
const arr = [1,2,3,4,6,true,"Dio Brando", false,10,"yare yare"];
const sum = arr.reduce( (sumSoFar, nextValue) => {
if ( typeof nextValue === "number" && isFinite(nextValue) ) {
return sumSoFar + nextValue;
}
//skip otherwise
return sumSoFar;
}, 0); //sum starting from zero
console.log(sum);Run Code Online (Sandbox Code Playgroud)