javascript - looping and decrementing sum -
i can't figure out why decrement sum won't work. work fine incrementing part, if first array value greater second doesn't seem run:
function sumall(arr) {   console.log(arr[0], arr[1]);   var sum = 0;   if (arr[0] < arr[1]) {     (var = arr[0]; <= arr[1]; i++) {       sum += i;       console.log(sum);     }   } else if (arr[0] > arr[1]) {     (var j = arr[1]; j >= arr[0]; j--) {       sum += j;       console.log("sec", sum);     }   }    return sum; }  sumall([9, 3]);      
already explained in comment, here code:
its because in loop have condition j >= arr[0] in else if have condition (arr[0] > arr[1]) , because of loops never gets executed. 
here working code:
function sumall(arr) {   console.log(arr[0], arr[1]);   var sum = 0;   if (arr[0] < arr[1]) {     (var = arr[0]; <= arr[1]; i++) {       sum += i;       console.log(sum);     }   } else if (arr[0] > arr[1]) {     (var j = arr[0]; j >= arr[1]; j--) {        sum += j;        console.log("sec", sum);     }   }    return sum; }  alert(sumall([9, 3]););      
Comments
Post a Comment