How to splice an element to the start of an array?

This question already has an answer here:

  • How can I add new array elements at the beginning of an array in JavaScript? 6 answers
  • JavaScript Array rotate() 16 answers

  • 尝试在for循环中移动数组:

    function rotate(arr, num){
        for(var i = 0; i < num; i++){
            item = arr[arr.length-1]
            arr.splice(arr.length-1, 1);
            arr.unshift(item)
        }
        return arr
    }
    
    alert(JSON.stringify(rotate(["Harry", "Sarah", "Oscar", "Tina"], 2)));
    alert(JSON.stringify(rotate(["Harry", "Sarah", "Oscar", "Tina"], 1)));

    You don't need a loop. First splice the last num elements off the end of the array, then splice them all onto the front.

    function rotate(arr, num) {
            var lastN = arr.splice(-num, num);
            [].splice.apply(arr, [0, 0].concat(lastN));
            return arr;
        }
    document.getElementById("result").innerHTML = JSON.stringify(rotate(["Harry", "Sarah", "Oscar", "Tina"], 2));
    <div id="result"></div>
    链接地址: http://www.djcxy.com/p/19354.html

    上一篇: 将一个对象推到数组的开头

    下一篇: 如何将元素拼接到数组的开头?