dimanche 4 août 2019

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?

I've tried using .reduce() and an arrow function with no success. 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.

//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 = []




Aucun commentaire:

Enregistrer un commentaire