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

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


当前回答

使用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

其他回答

var totally = eval(arr.join('+'))

这样你就可以在阵列中放置各种各样的异国情调的东西。

var arr = ['(1/3)','Date.now()','foo','bar()',1,2,3,4]

我只是半开玩笑。

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

我认为这是求和数组的简单方法

function sumArray(arr){

    let total = 0;

    for(i = 0; i<arr.length ; i++){

        total += arr[i];
    }
    return total;
}

console.log(sumArray([1,2,3,4,]));

    <!DOCTYPE html>
    <html>
    <body>

      <p>Click the button to join two arrays.</p>
      <button onclick="myFunction()">Try it</button>
      <p id="demo"></p>
    <script>
var hege = [1, 2,4,6,7,8,8];
var stale = [1, 2,4,5];
function myFunction() {
    console.log((hege.length > stale.length))    
    var children  = (hege.length > stale.length)? abc1() :abc2();       document.getElementById("demo").innerHTML = children;
}
function abc1(){
    console.log(hege,"Abc1")    
    var abcd=hege.map(function (num, idx) {
        console.log(hege.length , idx)
        return stale.length>idx?num + stale[idx]:num;
    })
    return abcd;
}

function abc2(){

    console.log(hege,"Abc2",stale)    
    var abcd=stale.map(function (num, idx) {
        console.log(hege.length , idx)
        return hege.length>idx?num + hege[idx]:num;
    })
    return abcd;
}
</script>

</body>
</html>
var total = 0;
$.each(arr,function() {
    total += this;
});