gpt4 book ai didi

javascript - 保持数组中的顺序,但更改索引的位置

转载 作者:行者123 更新时间:2023-12-03 11:59:36 24 4
gpt4 key购买 nike

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

1、2、3、4、5

变成了

2、3、4、5、1

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com