根据星期几获取星期几数组

时间:2020-04-24 17:03:12

标签: javascript

例如,如果我将星期数传递为3,我希望将数组排序为

weekStartDayNumber = 3

weekdays = ['wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'monday', 'tuesday']

如果我将week weekStartDayNumber设置为7,我希望数组按如下排序

weekdays = ['sunday',...'saturday']

需要根据weekStartDayNumber对数组进行排序。

function days(weekStartDayNumber) { //logic here}

4 个答案:

答案 0 :(得分:2)

const weekDays = ['monday', 'tuesday','wednesday', 'thursday', 'friday', 'saturday', 'sunday']

const days = (n) =>
  // Splice will take out everything from where ever you want to start until 
  // the end of the array and remove that part from the original. So
  // weekdays only contains whatever is left. So simply add the rest
  // using concat
  weekDays.splice(n - 1, weekDays.length - n + 1).concat(weekDays);

答案 1 :(得分:1)

const days = (n) => [...weekdays.slice(n-1), ...weekdays.slice(0, n-1)]

这应该做您需要的。一个不错的ES6小内衬。

答案 2 :(得分:1)

let a = function SortByDay(startNum) {
    let weekDays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
    return weekDays
        .slice(startNum - 1)
        .concat(weekDays
        .slice(0, startNum - 1));
};

答案 3 :(得分:0)

使用Array.slice()

function arrangeDays(startNum) {
    let days = ['monday', 'tuesday','wednesday', 'thursday', 'friday', 'saturday', 'sunday']
    let arrStart = days.slice(startNum-1)
    let arrEnd = days.slice(0, startNum-1)

    return arrStart.concat(arrEnd)
}

console.log(arrangeDays(3))
console.log(arrangeDays(7))