简体   繁体   English

需要帮助来了解javascript反向方法的重写解决方案的部分逻辑吗?

[英]Need help understanding part of the logic for a rewrite solution of the javascript reverse method?

So I was trying to understand this solution of rewriting the Array reverse method from scratch: 所以我试图理解这种从头开始重写Array反向方法的解决方案:

Array.prototype.reverse = function() {
  for(var i = 0, j = this.length-1; i < j; i++, j--) {
    var tmp = this[i];
    this[i] = this[j];
    this[j] = tmp;
  }
  return this;
 };

So I understand j starts as the amount of array elements - 1, and i is initially 0. And then I believe they are both incremented or decremented by 1 until i is no longer less than j..What I don't understand is the following lines: 因此,我知道j开始于数组元素的数量-1,而i最初为0。然后我相信它们都以1递增或递减,直到i不再小于j。我不了解的是以下几行:

    var tmp = this[i];
    this[i] = this[j];
    this[j] = tmp;

Could anyone anyone what is going on in these lines? 任何人都可以在这些方面发生什么吗?

Let's work through it with an example: 让我们通过一个示例来研究它:

// assume `this` = ["a", "b", "c"]
// assume i = 0 and j = 2

var tmp = this[i];
// tmp:  "a"
// this: ["a", "b", "c"]

this[i] = this[j];
// tmp:  "a"
// this: ["c", "b", "c"]

this[j] = tmp;
// tmp:  "a"
// this: ["c", "b", "a"]

Notice that step two is [c,b,c] and the [a] is totally gone. 请注意,第二步是[c,b,c][a]完全消失了。 This is why we save it to tmp, so that we can put it back in step three. 这就是为什么我们将其保存到tmp,以便可以将其放回第三步的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM