关于javascript:JS或其他解决方案中的shift()相反

Opposite of shift() in JS or other solutions

本问题已经有最佳答案,请猛点这里访问。

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

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

如预期,结果是[‘猫’、‘动物’、‘猪’、‘狗’]。我怎样才能让它以类似的方式做相反的事情呢?相反,我的意思是"猪"、"狗"、"猫"、"动物"。我试图找到与.shift()相反的结果,但找不到任何内容。谢谢你抽出时间来。


你可以1〔0〕。

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.

1
2
3
4
5
6
7
8
9
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"]


看起来您正在寻找一个rotate功能:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Array.prototype.rotate = (function() {
    // save references to array functions to make lookup faster
    var push = Array.prototype.push,
        splice = Array.prototype.splice;

    return function(count) {
        var len = this.length >>> 0, // convert to uint
            count = count >> 0; // convert to int

        // convert count to value in range [0, len)
        count = ((count % len) + len) % len;

        // use splice.call() instead of this.splice() to make function generic
        push.apply(this, splice.call(this, 0, count));
        return this;
    };
})();

a = [1,2,3,4,5];
a.rotate(1);
console.log(a.join(',')); //2,3,4,5,1
a.rotate(-1);
console.log(a.join(',')); //1,2,3,4,5
a.rotate(-1);
console.log(a.join(',')); //5,1,2,3,4