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!
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...
+ 2
the first thing I noticed that you didn't specify a data type in the array variable, at sumArray function
+ 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
+ 1
Thanks a lot! :)
+ 1
Brigi You're welcome :)
0
Rellot's screwdriver thanks for the comment, could you please explain how should I declare a type of the array?