Rotate the elements in an array in JavaScript

后端 未结 30 1831
走了就别回头了
走了就别回头了 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:07

    When I couldn't find a ready-made snippet to start a list of days with 'today', I did it like this (not quite generic, probably far less refined than the above examples, but did the job):

    //returns 7 day names with today first
    function startday() {
        const days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
        let today = new Date();
        let start = today.getDay(); //gets day number
        if (start == 0) { //if Sunday, days are in order
            return days
        }
        else { //if not Sunday, start days with today
            return days.slice(start).concat(days.slice(0,start))
        }
    }
    

    Thanks to a little refactor by a better programmer than me it's a line or two shorter than my initial attempt, but any further comments on efficiency are welcome.

提交回复
热议问题