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

Mystery Array Object behavior for Array Reversal

本文关键字:数组 对象 用于      更新时间:2023-09-26

我目前正在学习数据结构,并一直在探索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数组解构执行的最后一个数组交换调用