所以我试图理解这个从头开始重写数组反向方法的解决方案:
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;
};
所以我理解 j 从数组元素的数量 - 1 开始,i 最初为 0。然后我相信它们都增加或减少 1 直到 i 不再小于 j ..我不知道理解是以下几行:
var tmp = this[i];
this[i] = this[j];
this[j] = tmp;
有人知道这些行中发生了什么吗?
最佳答案
让我们通过一个例子来解决这个问题:
// 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"]
请注意,第二步是[c,b,c]
,并且[a]
完全消失了。这就是为什么我们将其保存到 tmp,以便我们可以在第三步中将其放回去。
关于javascript - 需要帮助理解 JavaScript 反向方法重写解决方案的部分逻辑吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26691296/