dimanche 20 décembre 2020

How can I add the numbers in the following code?

I have an array named arr = [[1,2],4] , and for loops to access the numbers. But I can't seem to add the last number. Why is it not working?

    let arr = [[1,2],4];       
    let total = 0;
        
    for(let i = 0; i < arr.length; i++) {
       for(let j = 0; j < arr[i].length; j++) {
          total += arr[i][j];
       }
    }
    console.log(arr.length)  // returns length = 2
    console.log(total);      // returns total = 3

Aucun commentaire:

Enregistrer un commentaire