大家好,我有这个任务: 我有一个数组[4,7,3,6,9],我必须做一个像这样的数组:
[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周左右,这是我目前的尝试:
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);
另外在我的脑海里,我有.push,.splice等。我不知道为什么,但我真的觉得javascript不适合我的大脑,哈哈:D
答案 0 :(得分:4)
你可以弹出值并取消它。
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 :(得分:0)
您可以将splice
与pop
结合使用:
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)
}
&#13;
答案 2 :(得分:0)
这是我的解决方案:
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);
}
答案 3 :(得分:0)
你可以使用swift并推送
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 );