JS while loop array [i ++]. How it works?

I wonder how it works. I assume that "right [r ++]" increments "r" in the while loop. Or does it show which element of “right” we click on the “result”?

function merge(left, right){
  var result = [],
      lLen = left.length,
      rLen = right.length,
      l = 0,
      r = 0;
  while(l < lLen && r < rLen){
     if(left[l] < right[r]){
       result.push(left[l++]);
     }
     else{
       result.push(right[r++]);
    }
  }  
  return result.concat(left.slice(l)).concat(right.slice(r));
}

Thanks.

+4
source share
2 answers
result.push(right[r++]);

is essentially a shorthand for

result.push(right[r]);
r = r + 1;

The ++ operator after a variable returns the value of the variable before it is incremented.

For comparison, using it before the variable

result.push(right[++r]);

will achieve the same result as

r = r + 1;
result.push(right[r]);
+4
source

right [r ++] is similar to writing this:

right[r]
r=r+1

This was called post-increment. There is also a preliminary increase. It would be written like this:

right[++r]

r=r+1
right[r]
0

Source: https://habr.com/ru/post/1624332/


All Articles