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

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


当前回答

我知道这是一个老帖子。但我只是想分享我对这个问题的看法。

let myArr = [1, 3, 4, 5, 6, 7, 8];
let counter = 0;
for(let i = 0; i < myArr.length; i++){
  counter = counter + myArr[i];
    console.log(counter);}

其他回答

也有人可以使用map()函数对数组值求和。

function sumOfArrVal(arr){
    let sum=0;
    arr.map(val=>sum+=val)
    return sum
}

let result=sumOfArrVal([1,2,3,4])
console.log(result)
var total = 0;
$.each(arr,function() {
    total += this;
});

使用reduce

设arr=[1,2,3,4];设和=arr.reduce((v,i)=>(v+i));console.log(总和);

了解底层流程的最简单答案:

let array = [10, 20, 30, 40, 50]
let total = 0

for(let i in array)
{
    total += array[i]
}

console.log(total)

&如果您已经熟悉底层流程,那么内置方法可以节省您的时间:

let array = [10, 20, 30, 40, 50]
let total = array.reduce((x, y) => x + y)
console.log(total)

一小段JavaScript代码就能完成这项工作:

var numbers = [1,2,3,4];
var totalAmount = 0;

for (var x = 0; x < numbers.length; x++) {

    totalAmount += numbers[x];
}

console.log(totalAmount); //10 (1+2+3+4)