javascript旋转数组元素

javascript rotate array elements

本问题已经有最佳答案,请猛点这里访问。

大家好,我有个任务:我有一个数组[4,7,3,6,9],我必须做一个这样的数组:

1
2
3
4
5
[4,7,3,6,9]
[9,4,7,3,6]
[6,9,4,7,3]
[3,6,9,4,7]
[7,3,6,9,4]

我必须制作一个程序,让数组在其中旋转,即使我向数组添加一个新项,它也会相应地改变。我是JS的新手,大约一周左右,下面是我目前的尝试:

1
2
3
4
5
6
7
8
9
10
var numbers = [4, 7, 3, 6, 9];
console.log(numbers);
numbers[0] = 9; numbers[1] = 4; numbers[2] = 7; numbers[3] = 3; numbers[4] = 6;
console.log(numbers);
numbers[0] = 6; numbers[1] = 9; numbers[2] = 4; numbers[3] = 7; numbers[4] = 3;
console.log(numbers);
numbers[0] = 3; numbers[1] = 6; numbers[2] = 9; numbers[3] = 4; numbers[4] = 7;
console.log(numbers);
numbers[0] = 7; numbers[1] = 3; numbers[2] = 6; numbers[3] = 9; numbers[4] = 4;
console.log(numbers);

在我的脑海里我也有,推,拼接等等。我不知道为什么,但我真的觉得javascript不适合我的大脑,哈哈:D。


您可以弹出该值并取消其iff。

1
2
3
4
5
6
7
8
var array = [4, 7, 3, 6, 9],
    i = array.length;

while (i--) {
    console.log(array.join(' '));
    array.unshift(array.pop());
}
console.log(array.join(' '));


你可以用快推

1
2
3
4
5
6
7
8
9
10
11
function rotate( array , times ){
while( times-- ){
var temp = array.shift();
 array.push( temp )
 }
}

//Test
var players = ['Bob','John','Mack','Malachi'];
rotate( players ,2 )
console.log( players );


这是我的解决方案:

1
2
3
4
5
6
7
var numbers = [4, 7, 3, 6, 9];

for(var i = 0; i < numbers.length; i++) {
    console.log(numbers);
    var lastElement = numbers.pop();
    numbers = [lastElement].concat(numbers);
}

您可以简单地将splicepop结合使用:

1
2
3
4
5
var arr = [4,7,3,6,9];
for(var i=0; i<arr.length-1; i++){
  arr.splice(0, 0, arr.pop())
  console.log(arr)
}