如何通过作用于数组本身或返回新数组的循环有效地滚动数组
arr = [1,2,3,4,5]
我想做这样的事情:
arr.scroll(-2)
arr now is [4,5,1,2,3]
最佳答案
使用Array.slice
:
> arr.slice(-2).concat(arr.slice(0, -2));
[4, 5, 1, 2, 3]
你can然后对其进行概括并使用 scroll
函数扩展 Array.prototype
:
Array.prototype.scroll = function (shift) {
return this.slice(shift).concat(this.slice(0, shift));
};
> arr.scroll(-2);
[4, 5, 1, 2, 3]
关于javascript - 循环滚动数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12379652/