我想找到一个数组中所有数字的总和。当用户单击页面上的图像时,这些数字将被推入数组。由于数组不断更新,我是否需要使用for循环或其他方法?

我尝试使用.reduce()和一个箭头函数没有成功。控制台返回一个错误,即数组中没有初始值,因此我将数字0放入其中,但该函数将不包含任何要插入的数字。

//user clicks HTML element
$("#yellowcrystal").on('click', function () {

 //value of number must differ from the other clicked HTML elements
     if (yellowCrystalNum !== redCrystalNum && yellowCrystalNum !==
     blueCrystalNum && yellowCrystalNum !== greenCrystalNum){
          crystals.push(yellowCrystalNum);
     } else {
          yellowCrystalNum = Math.floor(Math.random() * 13) + 1;
     }
});

//empty array to hold values
var crystals = []

最佳答案

也许是这样吗?

//user clicks HTML element
var crystals = []
var sum = 0;

$("#yellowcrystal").on('click', function () {

 //value of number must differ from the other clicked HTML elements
     if (yellowCrystalNum !== redCrystalNum && yellowCrystalNum !==
     blueCrystalNum && yellowCrystalNum !== greenCrystalNum){
        crystals.push(yellowCrystalNum);
        // use it here maybe
        sum = arrsum(crystals)
     } else {
          yellowCrystalNum = Math.floor(Math.random() * 13) + 1;
     }
});

function arrsum(arr) {
    return arr.reduce(function(xs, x) {
        return xs + x
    }, 0)
}

08-07 00:06