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

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


当前回答

这些都是很好的答案,但如果数字是按照问题(1,2,3,4)中的顺序排列的话,你可以通过应用公式轻松地做到这一点(n*(n+1))/2,其中n是最后一个数字

其他回答

非常简单

步骤1我们应该有一个数组,如:

const arrayNumber = [500,152,154,1555,12445];

第2步(如果需要,可以忽略这个步骤)要确保表中的所有值都是数字

let newArray = [];
for (let i = 0; i < arrayNumber.length; i++) {
        newArray.push(parseInt(arrayNumber[i], 10));
      }

步骤3

const sumInArray = dataData.reduce( (a, b) => a + b);

最后

console.log(sumInArray);

使用for循环:

const array = [1, 2, 3, 4];
let result = 0;

for (let i = 0; i < array.length - 1; i++) {
  result += array[i];
}

console.log(result); // Should give 10

甚至是forEach循环:

const array = [1, 2, 3, 4];
let result = 0;

array.forEach(number => {
  result += number;
})

console.log(result); // Should give 10

为简单起见,请使用reduce:

const array = [10, 20, 30, 40];
const add = (a, b) => a + b
const result = array.reduce(add);

console.log(result); // Should give 100

ES6用于。。属于

let total = 0;

for (let value of [1, 2, 3, 4]) {
    total += value; 
}

这些都是很好的答案,但如果数字是按照问题(1,2,3,4)中的顺序排列的话,你可以通过应用公式轻松地做到这一点(n*(n+1))/2,其中n是最后一个数字

getTotal = (arr) => {
    let total = 0
    for (let i = 0; i < arr.length; i++) {
        total += arr[i];
    }
    return total
}

getTotal([1, 2, 3, 4]) // 10
getTotal([1, 2, 3, 4, 5]) // 15