试着理解这个函数:Array.prototype.reverse = function(){
Trying to understand this function: Array.prototype.reverse = function() {
当调用此方法时,它将反转原始数组中项的顺序。然后它返回原来的那个数组。不需要创建新的数组来传递此类型。然而,我正试图弄清楚this.push(arr.pop());
在这个函数中的工作原理。
Array.prototype.reverse = function() {
var arr = this.splice(0); //I understand first we remove all the items in the array starting from [0]
while(arr.length) { //then we run the arr.length of all the items?
this.push(arr.pop()); //then add the deleted last item? doesn't make sense...
}
return this;
};
测试用例:Test.assertSimilar([1, 2, 3, 4].reverse(), [4,3,2,1]);
Test.assertSimilar(["a", "b", "c"].reverse(), ["c", "b", "a"]);
Test.assertSimilar([].reverse(), []);
或者写一个你认为更好的解决方案
我已经添加了注释:
Array.prototype.reverse = function() {
var arr = this.splice(0); // Removes all entries from `this` array AND returns
// them in a new array
while(arr.length) { // For as long as that new array still has items
// (length is "truthy" until it's 0)
this.push(arr.pop()); // `pop` removes the LAST entry from `arr`, and
// `push` adds it to `this` as the next entry
}
return this;
};
假设我们有[1, 2, 3, 4, 5]
:
- 首先将这些从
this
中移除并放入arr
中。 - 然后,因为
arr.length
是5
,我们进入循环体。 -
arr.pop()
将5
从arr
中移除 -
this.push()
将5
添加到this
的下一个可用位置,即 -
arr.length
现在是4
,所以我们再次进入body -
arr.pop()
将4
从arr
中移除 -
this.push()
将4
添加到this
的下一个可用位置,就在5
之后 - 冲洗,重复
- 当
arr.length
为0
时,它不再为真,我们退出循环
"或者写一个你认为更好的函数"
这里有一个更有效和更简单的解决方案:
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;
};
在支持ECMAScript 6的浏览器中,你可以把它缩短为:
Array.prototype.reverse = function() {
for (var i = 0, j = this.length - 1; i < j; i++, j--) {
[this[i], this[j]] = [this[j], this[i]];
}
return this;
};
不确定是否有额外的开销
相关文章:
- 直接在函数声明上使用function.prototype.bind
- 如何迭代Array.prototype函数
- 我怎样才能制作一个“;reverse preventDefault”;在jQuery中
- Object.prototype using 'this'
- 在不兼容的接收器上调用的方法Set.prototype.add未定义
- 为什么可以't我用Set对象调用Array.prototype.map
- ExtJS 4 Object.prototype fail
- 如何通过Prototype或jquery移除子类的父类基类
- 复选框:使用Array.prototype.forEach调用推送选中订单,
- 将setTimeout()包装器实现为Element.prototype中的方法
- Object.prototype.hasOwnProperty.call() vs Object.prototype.h
- 如何通过 Function.prototype.apply() 更改调用函数的参数
- Function.prototype.call和Function.protoype.all只应用一个参数
- 使用JavaScript或Prototype获取表单中的所有控件并启用它们
- JavaScript-使用B.prototype=new A()继承数组
- 转换类似数组的对象Array.prototype.slice或Array.from
- requestAnimationFrame的Function.prototype.bind导致属性不可读
- Javascript中的Array.prototype.reverse和Array.reverse有什么区别
- jQuery和prototype不能与Array.prototype.reverse一起工作
- 试着理解这个函数:Array.prototype.reverse = function(){