循环滚动数组

scroll an array with looping

本文关键字:数组 滚动 循环      更新时间:2023-09-26

如何在循环作用于数组本身或返回新数组的情况下有效滚动数组

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]

然后可以对其进行推广,并使用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]