javascript - 与 JS 或其他解决方案中的 shift() 相反

标签 javascript

<分区>

我正在尝试获取一个数组并让它围绕自身循环。我已经找到了一个简单的解决方案,让它向后循环:

array = ['Dog', 'Cat', 'Animal', 'Pig']
array[array.length] = array[0];
array.shift();

正如预期的那样,结果为 ['Cat', 'Animal', 'Pig', 'Dog']。我如何让它以类似的方式做相反的事情。通过做相反的事情,我的意思是变成 ['Pig', 'Dog', 'Cat', 'Animal']。我试图为此找到 .shift() 的反义词,但找不到任何东西。感谢您的宝贵时间。

最佳答案

你可以 Array#pop

The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

Array#unshift .

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

var array = ['Dog', 'Cat', 'Animal', 'Pig'];

array.push(array.shift());
console.log(array); // ["Cat", "Animal", "Pig", "Dog"]

array = ['Dog', 'Cat', 'Animal', 'Pig'];

array.unshift(array.pop());
console.log(array); // ["Pig", "Dog", "Cat", "Animal"]

关于javascript - 与 JS 或其他解决方案中的 shift() 相反,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44133564/

相关文章:

javascript - ExtJS 5 : bind to other class properties, 像 allowBlank

javascript - 触发点击带有主题标签的 URL

javascript - 样式属性中的索引与 native react

javascript - 更改仅适用于表中的第一行

javascript - 相似 URL 的正则表达式模式匹配

javascript - 使用 foreach knockout 渲染复选框

javascript - 如何避免 TopoJSON 内存错误

JavaScript 确认函数返回 false

javascript - 将 +1 添加到只读文本输入字段的 jQuery 值

javascript - Three.js 和加载跨域图片