How to find the sum of an array of numbers

后端 未结 30 2591
醉话见心
醉话见心 2020-11-21 13:36

Given an array [1, 2, 3, 4], how can I find the sum of its elements? (In this case, the sum would be 10.)

I thought $.each might be useful,

30条回答
  •  北恋
    北恋 (楼主)
    2020-11-21 14:30

    Use a for loop:

    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
    

    Or even a forEach loop:

    const array = [1, 2, 3, 4];
    let result = 0;
    
    array.forEach(number => {
      result += number;
    })
    
    console.log(result); // Should give 10
    

    For simplicity, use reduce:

    const array = [10, 20, 30, 40];
    const add = (a, b) => a + b
    const result = array.reduce(add);
    
    console.log(result); // Should give 100
    

提交回复
热议问题