给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)

我认为每个美元可能有用,但我不确定如何实现它。


当前回答

您可以使用for of循环求和,如下所示:

let arr = [1, 2, 3, 4];
let total = 0;
for (let i of arr) {
  total += i;
}
console.log(total)

其他回答

只需使用此功能:

function sum(pArray)
{
  pArray = pArray.reduce(function (a, b) {
      return a + b;
  }, 0);

  return pArray;
}

函数和(pArray){pArray=pArray.reduce(函数(a,b){返回a+b;}, 0);返回pArray;}var arr=[1,4,5];console.log(总和(arr));

var total = 0;
$.each(arr,function() {
    total += this;
});

试试这个。。。

function arrSum(arr){
    total = 0;  
    arr.forEach(function(key){
        total = total + key;            
    });
    return total;
}
arr.reduce(function (a, b) {
    return a + b;
});

参考:Array.prototype.reduce()

一个“重复”问题问如何对二维数组执行此操作,因此这是一个简单的适应问题。(区别仅在于六个字符[2],0,它在每个子数组中找到第三项,并传递初始值0):

常量二维数组=[[10, 10, 1],[10, 10, 2],[10, 10, 3],];constsum=twoDimensionalArray.reduce((partial_sum,a)=>partial_sum+a[2],0);console.log(总和);//6.