我想制作一个更改数组的函数,以便顺序保持不变,但是索引的位置已更改:例如

1, 2, 3, 4, 5

变成

2, 3, 4, 5, 1

我的问题是我遇到了无限循环,我认为这与代码i != one有关。另外,代码中的i != one有什么问题?

var switchArray = function(arrayOne){
  //save the original arrayOne[0] with var one
  var one = arrayOne[0];
  //loop around until i = the original [0]; i originally = one - the length of the array so it equals the last index.
  for(var i = arrayOne[arrayOne.length - 1]; i != one;){
    // set var b = var i ( the last index of the array)
    var b = arrayOne[arrayOne.length - 1];
    //delete the last index of the array
    arrayOne.pop(arrayOne[arrayOne.length - 1]);
    //add var b to the array as the first index
    arrayOne.unshift(b);
  }
  return arrayOne;
}

最佳答案

您可以一行完成:

var array = [1, 2, 3, 4, 5];
array.push(array.shift());

console.log(array); // => [2, 3, 4, 5, 1]


参见JSFiddle

关于javascript - 保持数组顺序,但更改索引位置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25474936/

10-12 15:40