数组反转的神秘数组对象行为

时间:2016-07-03 06:26:51

标签: javascript arrays object data-structures iteration

我目前正在研究数据结构并一直在探索javascript。在Place Place方法中编写反向数组时,我一直坚持这个问题。我查看了Array Objects,Object.prototype和函数对象的文档,但我找不到正在发生的事情的答案。也许我有一个逻辑错误,这里是代码:

//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" ]

为了尝试调试,我写了几个console.log来跟踪当前实例中的迭代器和数组元素以及复制的数组。

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

非常感谢任何见解。

3 个答案:

答案 0 :(得分:0)

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;
}

答案 1 :(得分:0)

这里的主要问题是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]];
  }
}

答案 2 :(得分:-1)

你可以在O(n / 2)时间内做到这一点。

&#13;
&#13;
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());
&#13;
&#13;
&#13;

增加i东西虽然很棘手。这个位置是ES6数组解构执行中数组交换的最后一次调用..