简体   繁体   English

如何将最后一项移动到 Javascript 中的数组开头

[英]How to move last item to start of array in Javascript

How can I move the last item in an array to the start?如何将数组中的最后一项移动到开头?

So, for example, I have the array ["a", "b", "c"] .因此,例如,我有数组["a", "b", "c"] How do I make it ["c", "a", "b"] ?我如何使它成为["c", "a", "b"]

let a = ["a", "b", "c"]

a.unshift(a.pop())

Array.slice() is a good start, and it doesn't modify the original array. Array.slice()是一个好的开始,它不会修改原始数组。 Here's a small algorithm using `Array.slice() and supporting wrap around:这是一个使用 `Array.slice() 并支持环绕的小算法:

 let rotatingSlice = (a, start, end) => { if (start < 0 && end > a.length) return a.slice(start).concat(a.slice(0, end)); if (start < 0) return a.slice(start).concat(a.slice(0, end)); else if (end > a.length) return a.slice(start).concat(a.slice(0, end % a.length)); else return a.slice(start, end); }; let array = [0,1,2,3,4,5,6,7]; console.log(rotatingSlice(array, 0, 3)) // 1st 3 elements console.log(rotatingSlice(array, -3, 0)) // last 3 elements console.log(rotatingSlice(array, -3, 3)) // last 3 and 1st 3 elements console.log(rotatingSlice(array, 4, 4 + array.length)) // the array starting at the middle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM