我的反转数组代码有什么问题?

3
这是我的代码:

function reverseArray(array){
  var newArray = [];
  for (i = 0; i <= array.length + 1; i++)
    newArray.unshift(array.shift());
  return newArray;
};

我不理解为什么for循环中的条件不是i < array.length。例如,当数组有3个元素时,我认为你需要循环遍历数组3次,将每个元素移动到新数组中,但出于某种原因,当我尝试它(例如console.log(reverseArray(["a", "b", "c"])))时,我必须将它更改为当前的i <= array.length + 1;才能得到正确的输出["c", "b", "a"]。我不明白为什么,如果有人能够帮助解释为什么i < array.length不起作用,我会非常感激。谢谢!

3
每轮迭代后array.length的值都不同,因为你正在对数组进行shift操作。在循环之前将其值存入一个变量中,并将该变量用于条件中。顺便说一下,有一个名为reverse的方法 - Blackhole
谢谢!我现在理解了。我知道reverse方法,这只是一个教程的练习。 - ben432rew
可以使用 var v; while(v = a.shift()) b.unshift(v); 进行操作。 - levi
2个回答

2
  1. your code is error in the if condition check, because every time the condition is be checked in the for statement, so the array.lenght is changed every time, and the condition should not be array.length + 1, you can try the code below

    function reverseArray(array){
      var newArray = [];
      for (var i = 0,len=array.length; i < len; i++)
        newArray.unshift(array.shift());
      return newArray;
    };
    
  2. I suggest to use the reverse method of the Array, but if you want to make a new copy of the array, you can use Array.slice(), try this:

    function reverseArray(array){
        var newArray=array.slice()
        newArray.reverse()
        return newArray
    }
    

因为你知道数组的长度,所以你可以使这个函数更加高效。请看一下这些基准测试来比较这些解决方案。只是为了给你一个基本的想法,我的解决方案与你的略有不同,但速度却快了10倍以上。我强烈鼓励所有人学习动态扩展数组的性能成本。 - maček
我知道使用unshift和splice方法的性能问题,我建议使用reverse方法,但是我测试了基准测试,似乎使用你的方法具有最佳性能。 - powerfj

1

如果由于某种原因无法使用Array.prototype.reverse,那么我将编写以下函数

function reverseArray(arr) {
  var len = arr.length;
  var rev = new Array(len);
  for (var i=0, j=len-1; i<len; i++, j--) {
    rev[i] = arr[j];
  }
  return rev;
}

reverseArray([1,2,3]);
// [3,2,1]

你可以查看这个解决方案主导基准测试。它甚至比使用10元素数组(在Chrome中测试)的本地Array.prototype.reverse更快。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接