Rotate the elements in an array in JavaScript

后端 未结 30 1791
走了就别回头了
走了就别回头了 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 11:19

    Non mutating solution

    var arr = ['a','b','c','d']
    arr.slice(1,arr.length).concat(arr.slice(0,1)
    

    with mutation

    var arr = ['a','b','c','d']
    arr = arr.concat(arr.splice(0,1))
    

提交回复
热议问题