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

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -