保持数组中的顺序,但改变索引的位置

时间:2014-08-24 18:27:43

标签: javascript arrays

我想创建一个更改数组的函数,使顺序保持不变,但索引的位置会发生变化:例如

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

1 个答案:

答案 0 :(得分:1)

您可以在一行中完成:

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

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

JSFiddle