是否有更短的方式来分配值而不是“if-else”链?

时间:2017-06-13 07:04:02

标签: javascript if-statement optimization

现在,我的代码是这样的:

var day = getDay(); //A function that gets this current day of the week as integer
var dayname = "";
if (day==0) dayname = "Su";
if (day==1) dayname = "Mo";
...
if(day==6) dayname = "Sa";

它有效,但我觉得它可能会更短,就像这样:

if (day == (0,1,2,3,4,5,6)) dayname = ("Su","Mo",...,"Sa");

有办法吗?

5 个答案:

答案 0 :(得分:2)

var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var dayname = days[getDay()];

答案 1 :(得分:0)

你可以这样做:

var dayNames = ['mo', 'tu', 'we', 'th', 'fr', 'sa', 'su'];
var dayName = dayNames[getDay()];

这样就没有if语句。如果day从1开始并在7结束,则可以执行以下操作:

var dayName = dayNames[getDay() - 1];

答案 2 :(得分:0)

您可以使用以下方法

将数组定义为var days = ['Su', 'Mo', 'Tue', 'Thu', 'Fri', 'Sat'];并使用索引0-6选择特定日期。

因此,如果getDay();返回0,那么它会将sun存储在dayname

var day = getDay(); //A function that gets this current day of the week as integer
var days = ['Su', 'Mo', 'Tue', 'Thu', 'Fri', 'Sat'];
var dayname = days[day];

答案 3 :(得分:0)

您需要的是查找表:

var day = getDay();
var daysByNumber = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];
var dayName = daysByNumber[day];

答案 4 :(得分:0)

另一种方法是使用字典

    var day = getDay();
    dict = {0: 'Monday', 1: 'Tudesday', 2: 'Wednesday', 3: 'Thursday', 4: 'Friday', 5: 'Saturday', 6: 'Sunday'}
    dayname=dict[day]
    print(dayname)