简体   繁体   English

如何对被推入初始为空的数组的索引项求和?

[英]How can you sum index items that are being pushed into an array that is initially empty?

I want to find the sum of all numbers in an array.我想找到数组中所有数字的总和。 The numbers are being pushed into the array when the user clicks an image on the page.当用户单击页面上的图像时,数字将被推送到数组中。 Do I need to use a for loop or something different since the array is continuously being updated?由于数组不断更新,我是否需要使用 for 循环或不同的东西?

I've tried using .reduce() and an arrow function with no success.我尝试使用 .reduce() 和箭头函数但没有成功。 The console is returning an error that there is no initial value in the array, so I put the number 0 in there, but the function won't include any of the numbers being pushed in.控制台返回一个错误,指出数组中没有初始值,所以我将数字 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 = []

Maybe like this?也许像这样?

//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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM