0

Please help to write a function to get a sum of numbers in the array

I need to write a function that finds a sum for any array you enter, but it seems like I cannot find the right solution... I made 2 attempts to solve it, for loop and for...of loop: function sumArray(array){ /* let total =0; for( let i = 0; i < array.length; i++){ let total = array[i]; } return total; }*/ let total = 0; for( let num of array){ total += array[num]; } return total; } Could you help me to find my error please? thanks in advance!

1st Sep 2021, 12:55 PM
Brigi
Brigi - avatar
6 Respuestas
+ 4
//your code goes here function sumArray(array){ /* let total =0; for( let i = 0; i < array.length; i++){ total += array[i]; } return total; */ let total = 0; for( let num of array){ total += num; } return total; } console.log(sumArray ([1,2,3,4])) //Both are correct...
1st Sep 2021, 1:19 PM
Rupali Haldiya
Rupali Haldiya - avatar
+ 2
the first thing I noticed that you didn't specify a data type in the array variable, at sumArray function
1st Sep 2021, 12:57 PM
Rellot's screwdriver
Rellot's screwdriver - avatar
+ 2
Brigi In forOf loop the initialiser is considered as the element of iterator, so you've no need to write total += array[num] you can simply write total += num, bcz num is not defining index of array element, its element of array by itself
1st Sep 2021, 1:16 PM
Rupali Haldiya
Rupali Haldiya - avatar
+ 1
Thanks a lot! :)
1st Sep 2021, 1:24 PM
Brigi
Brigi - avatar
+ 1
Brigi You're welcome :)
1st Sep 2021, 1:34 PM
Rupali Haldiya
Rupali Haldiya - avatar
0
Rellot's screwdriver thanks for the comment, could you please explain how should I declare a type of the array?
1st Sep 2021, 1:25 PM
Brigi
Brigi - avatar