最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JS while loop array[i++]. How does it work? - Stack Overflow

programmeradmin0浏览0评论

I'm wondering how it works. I guess that "right[r++]" increments "r" in while loop. Or it shows which element of "right" we push to "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));
}

Thank you.

I'm wondering how it works. I guess that "right[r++]" increments "r" in while loop. Or it shows which element of "right" we push to "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));
}

Thank you.

Share Improve this question asked Jan 14, 2016 at 18:55 Tima TruTima Tru 1861 gold badge4 silver badges17 bronze badges 1
  • the question is, what does not work, what is your problem? – webdeb Commented Jan 14, 2016 at 19:02
Add a ment  | 

2 Answers 2

Reset to default 6
result.push(right[r++]);

is essentially shorthand for

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

The ++ operator after the variable returns the variable's value before it gets incremented.

For parison, using it before the variable

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

would achieve the same result as

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

right[r++] is same like writing this:

right[r]
r=r+1

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

right[++r]

It would be eqvivalent to

r=r+1
right[r]
发布评论

评论列表(0)

  1. 暂无评论