Search code examples
javascriptcycle

Why am I getting value increase while recalculating an array?


I need to recalculate vales of array in JavaScript and I am trying to do it like this:

        for (var i = 0; i < totalNum; i++) {
          x = 3;
          if (chane[i]<rand) {
            chane[i+1] += chane[i];
            chane[i] = 0;
          } else{
            chane[i] -= x;
            chane[i+1] += x;
          };

chane array comes in with values [15,4,4,0], and comes out as [12,40,40,3]. totalNum is 4.

I have been staring at this code trying to find where my newbie mistake hides... I am new to JavaScript, so this very well may be just some syntax error.


Solution

  • You forgot to convert your value to integer, and you should pass string value to your loop check this code:

        for (var i = 0; i < totalNum; i++) {
          // convert to int by mul to 1
          chane[i]*=1;
          chane[i+1]*=1;
    
          x = 3;
          if (chane[i]<rand) {
            chane[i+1] += chane[i];
            chane[i] = 0;
          } else{
            chane[i] -= x;
            chane[i+1] += x;
          };
        }
    

    if you set chane = [15,4,4,0] and set totalNum = 4, the result is: [12, 4, 4, 0, NaN] and NaN is for check last value because when i=3 then chane[3] equal with 0 and chane[i+1] equal to undefined and undefined multiply to every number is NaN, you can fix it with change upper bound (in your example:set totalNum to 3, fixed it with changing to totalNum = chane.length-1) or add some if