gpt4 book ai didi

javascript - 如何让这个程序化 JS 变得更加实用呢?

转载 作者:行者123 更新时间:2023-12-03 10:25:47 25 4
gpt4 key购买 nike

鉴于此函数根据用户设置对数组重新排序...

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']

如何在使用更少的状态和变量的同时使其功能更强大?

最佳答案

这个怎么样?

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];
});
}

关于javascript - 如何让这个程序化 JS 变得更加实用呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29406926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com