0
Where I go wrong?
I have to write a code for a function that calculate sum of only positive numbers or if there is nothing then return 0 here is code function positiveSum(arr) { var sum; for(let i=0; i <= arr.length; i++){ let temp = arr[i]; if(temp > 0){ sum+=arr[i] } else { sum = 0; } } return sum; }
3 ответов
+ 3
And initialize <sum> once just before the loop starts
var sum = 0;
+ 2
when temp is not positive, you are reseting the sum to 0
0
Your code is almost correct. You need to initialize the value of sum to 0 before starting the loop. If arr is an empty array, then sum should remain 0, otherwise it will result in undefined.
Here is the corrected code:
function positiveSum(arr) {
var sum = 0;
for(let i=0; i < arr.length; i++){
let temp = arr[i];
if(temp > 0){
sum+=arr[i]
}
}
return sum;
}