Rotate the elements in an array in JavaScript

后端 未结 30 1607
走了就别回头了
走了就别回头了 2020-11-22 10:55

I was wondering what was the most efficient way to rotate a JavaScript array.

I came up with this solution, where a positive n rotates the array to the

30条回答
  •  不要未来只要你来
    2020-11-22 11:05

    You can use push(), pop(), shift() and unshift() methods:

    function arrayRotate(arr, reverse) {
      if (reverse) arr.unshift(arr.pop());
      else arr.push(arr.shift());
      return arr;
    }
    

    usage:

    arrayRotate(['h','e','l','l','o']);       // ['e','l','l','o','h'];
    arrayRotate(['h','e','l','l','o'], true); // ['o','h','e','l','l'];
    

    If you need count argument see my other answer: https://stackoverflow.com/a/33451102

提交回复
热议问题