javascript旋转数组元素 [英] javascript rotate array elements
本文介绍了javascript旋转数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,我有这个任务:我有一个数组[4,7,3,6,9],我必须制作一个像这样的数组:
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]
即使我向数组添加新项目,我也必须编写一个数组旋转的程序.我是JS的新手,大约1周左右,这是我目前的尝试:
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);
在我看来,我也有.push,.splice等.我不知道为什么,但是我真的觉得javascript不适合我的大脑,哈哈:D
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
推荐答案
您可以弹出该值并将其取消移位.
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(' '));
这篇关于javascript旋转数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文