2017-05-23 63 views
2

我想要一個數組,並讓它循環。我已經找到一個簡單的解決方案,它具有循環本身周圍向後:在JS或其他解決方案中shift()的相反

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

此預期原來爲[「貓」,「動物」,「豬」,「狗」。我將如何使它以相似的方式做相反的事情。通過做相反的事情,我的意思是轉出['豬','狗','貓','動物']。我試圖找到與此相反的.shift(),但找不到任何東西。感謝您的時間。

+0

對面是[不印字(HTTPS:/ /developer.mozilla.org/docs/Web/JavaScript/Reference/Glo bal_Objects /陣列/不印字)? – evolutionxbox

+0

'Array#reverse()'顛倒了數組,看起來你在問什麼 – charlietfl

回答

1

你可以Array#pop

pop()方法刪除數組中的最後一個元素並返回該元素。此方法更改數組的長度。

Array#unshift

unshift()方法將一個或多個元素添加到數組的開頭,並返回該數組的新長度。

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"]

0

看起來你正在尋找一個rotate功能:移

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

相關問題