鉴于此功能可根据用户设置重新排序数组...
function getDayNamesInUserOrder() {
var dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var weekStartDayIndex = 2; // user has set this to be 2 (Tuesday)
// remove the first n days from the front of the array...
var daysSlicedFromStart = dayNames.splice(0, weekStartDayIndex);
// and stick them onto the end of it.
var dayNamesInUserOrder = dayNames.concat(daysSlicedFromStart);
return dayNamesInUserOrder;
}
getDayNamesInUserOrder();
=> ['Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun', 'Mon']
在使用较少的状态和变量时,如何使其更具功能性?
答案 0 :(得分:2)
这个怎么样?
function getDayNamesInUserOrder(offset) {
var dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
return [0,1,2,3,4,5,6].map(function (i) {
return dayNames[(i+offset) % 7];
});
}
答案 1 :(得分:0)
你可以这样做:
function getDayNamesInUserOrder(startIndex) {
var dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var result = [];
for (var i = 0; i < dayNames.length; i++) {
result.push(dayNames[(startIndex + i) % dayNames.length]);
}
return result;
}
演示:http://jsfiddle.net/jfriend00/ddhagb33/
仅供参考,似乎很难找到“功能性编程”的清晰定义。我能找到的是:
此功能满足这两个要求(与原始功能一样)。如果你有一个更具体的“更具功能性”的愿望,那么请准确描述你所追求的目标。
答案 2 :(得分:-1)
function getDayNamesInUserOrder() {
var dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var weekStartDayIndex = 2; // user has set this to be 2 (Tuesday)
return dayNames.concat(dayNames).slice(weekStartDayIndex, weekStartDayIndex + 7);
}