1

如何通过循环作用于数组本身或返回一个新数组来有效地滚动数组

arr = [1,2,3,4,5]

我想做这样的事情:

arr.scroll(-2)

arr now is [4,5,1,2,3]
4

1 回答 1

4

Use Array.slice:

> arr.slice(-2).concat(arr.slice(0, -2));
[4, 5, 1, 2, 3]

You can then generalize it and extend Array.prototype with the scroll function:

Array.prototype.scroll = ​function (shift) {
    return this.slice(shift).concat(this.slice(0, shift));
}​;

> arr.scroll(-2);
[4, 5, 1, 2, 3]
于 2012-09-12T00:20:20.750 回答