用于数组反转的神秘数组对象行为
Mystery Array Object behavior for Array Reversal
我目前正在学习数据结构,并一直在探索javascript。我一直被困在这个问题上写一个反向数组的地方方法。我看过数组对象的文档,对象。原型和功能对象,但我找不到答案是什么正在发生。也许我有一个逻辑错误,下面是代码:
//Reverse Array in Place Exercise
Array.prototype.tRev = function()
{
var nRay = this.valueOf(); //copy current instance of array
for (var x = 0,y = this.length-1; x < this.length; x++,y--)
{
this[x] = nRay[y]; //switch array element with copy of nRay (original elements)
}
}
这个方法给了我不熟悉的结果。
var z = [1,2,3,4,5];
var z1 = [343,32423,2434,4,5,5,3];
var z2 = ['hello','hi','goodbye'];
z.tRev(); //console -- > Array [ 5, 4, 3, 4, 5 ]
z1.tRev(); //console -- > Array [ 3, 5, 5, 4, 5, 5, 3 ]
z2.tRev(); //console -- > Array [ "goodbye", "hi", "goodbye" ]
为了尝试调试,我写了几个控制台。跟踪当前实例和复制数组中的迭代器和数组元素的日志。
var z = [1,2,3,4,5];
z.tRev();
undefined
current x is = 1 new copy of y is = 5
x iterator is = 0 z iterator is = 4
new x is = 5 old copy of y is = 5
current x is = 2 new copy of y is = 4
x iterator is = 1 z iterator is = 3
new x is = 4 old copy of y is = 4
current x is = 3 new copy of y is = 3
x iterator is = 2 z iterator is = 2
new x is = 3 old copy of y is = 3
current x is = 4 new copy of y is = 4
x iterator is = 3 z iterator is = 1
new x is = 4 old copy of y is = 4
current x is = 5 new copy of y is = 5
x iterator is = 4 z iterator is = 0
new x is = 5 old copy of y is = 5
Array.prototype.tRev = function()
{
var nRay = this.valueOf(); //copy current instance of array
for (var x = 0,y = this.length-1; x < y; x++,y--)
{ var tmp = this[x];
this[x] = this[y]; //switch array element with copy of nRay (original elements)
this[y] = tmp
}
return this;
}
这里的主要问题是this.valueOf()
没有复制数组。如果你想要一个副本,你应该使用this.slice()
。但如果你复制了一份,那么就地逆转又有什么意义呢?
Array.prototype.tRev = function() {
for (var x = 0; x < this.length / 2; x++) {
var y = this.length - x - 1;
var swap = this[x];
this[x] = this[y];
this[y] = swap;
}
}
编辑:如果你喜欢使用ES6:
Array.prototype.tRev = function() {
for (var x = 0; x < this.length / 2; x++) {
var y = this.length - x - 1;
[this[y], this[x]] = [this[x], this[y]];
}
}
您可以在O(n/2)时间内完成此操作。
var z = [1,2,3,4,5],
z1 = [343,32423,2434,4,5,5,3],
z2 = ['hello','hi','goodbye'];
Array.prototype.tRev = function(){
var i = 0,
len = this.length,
limit = Math.floor(len/2);
while (i <= limit) [this[i],this[len-1-i++]] = [this[len-1-i],this[i]];
return this;
};
console.log(z.tRev()); // in place reversed
console.log(z1.tRev());
console.log(z2.tRev());
增加i
的东西只是棘手的,虽然。这个位置是ES6数组解构执行的最后一个数组交换调用
相关文章:
- 将数组对象传递到struts2中的操作类
- 如何使用jquery返回php-json数组对象
- 从其名称获取javascript数组对象
- 值未与数组对象绑定
- 如何按数组/对象值的倍数过滤对象数组
- 在表中显示数组对象
- 在数组对象中分组
- 将第二个或多个数组推送到数组对象 AngularJS 中
- 重新排列 JavaScript 数组/对象
- 键上的javascript数组对象过滤器
- handontable:在不更改数据数组/对象的情况下隐藏某些列
- 用于跟踪购物车可用性的Javascript数组/对象/哈希表
- 重建有角度的java脚本数组对象
- 对JSON数组对象进行排序
- 连接与数组对象相关的文本:方式和位置
- 哪些浏览器和版本支持将常见的类数组对象直接传递到fn.apply()
- 如何使用Handlebars循环数组对象和模板
- 是否可以引用JS数组/对象中的另一个元素
- Javascript中的名称索引-数组/对象
- 数组长度不等于数组对象