如何用reduce仅求和具有不同值类型的数组中的数字?

-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)

Dun*_*ker 5

您需要进行以下更改:

  • (ab)应该是(a,b),它具有参数的功能
  • 没有“ typeOf.a”之类的东西,应该是“ typeof a”

我用一些更有用的变量名重写了代码,以解释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)