javascript rotate array elements [duplicate]

半腔热情 提交于 2020-12-12 06:17:18

问题


Hello, everybody, I have this task: I have an array [4,7,3,6,9] and I have to make an array like this:

[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]

I have to make a program where array is rotating even if I add a new item to an array it should change accordingly. I am total newbie at JS, 1 week or so, here is my current try:

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

Also in my mind I have .push, .splice, etc. I dont know why but i really feel that javascript is not for my brain, haha :D


回答1:


You could pop the value and unshift it.

var array = [4, 7, 3, 6, 9],
    i = array.length;

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



回答2:


you can use swift and push

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



回答3:


You can simply use splice in conjunction with 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)
}



回答4:


This is my solution:

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


来源:https://stackoverflow.com/questions/49359411/javascript-rotate-array-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!