如何缩短JavaScript if / else语句?

时间:2013-11-21 22:59:32

标签: javascript function if-statement shortcut

我有一个基于很多if / else语句的函数。这个函数没有问题,但我想知道是否有更短的方法来重写它?

month = get_month(field.value); //this is inside another function

function get_month(m){ if(m==='January'){return'01';} else if(m==='Febuary'){return'02';} else if(m==='March'){return'03';} else if(m==='April'){return'04';} else if(m==='May'){return'05';} else if(m==='June'){return'06';} else if(m==='July'){return'07';} else if(m==='August'){return'08';} else if(m==='September'){return'09';} else if(m==='October'){return'10';} else if(m==='November'){return'11';} else if(m==='December'){return'12';}}

之前我已经看过并使用过这个,但我不知道是否会按照这种规模运作:

var x = y !== undefined ? y : 1;

8 个答案:

答案 0 :(得分:4)

一个对象可以很好地适应这种情况。

function getMonth(m) {
  var months = {
    January: "01",
    February: "02",
    March: "03",
    April: "04",
    May: "05",
    June: "06",
    July: "07",
    August: "08",
    September: "09",
    October: "10",
    November: "11",
    December: "12"
  }
  return months[m];
}

您可以在此jsFiddle demo上看到这一点。

答案 1 :(得分:2)

您可以执行类似

的操作
var monthNumbers = {
  "January": "01",
  "February": "02",
  //...
  "December": "12",
};

var getMonth = function(m) {
  return monthNumbers[m];
};

更好的是,如果你在JavaScript中处理日期/时间,我强烈推荐moment.js

答案 2 :(得分:1)

使用密钥数组:

var month = {
  January : "01",
  Febuary : "02",
  March : "03",
  April : "04",
  May : "05",
  June : "06",
  July : "07",
  August : "08",
  September : "09",
  October : "10",
  November : "11",
  December : "12"
}

function get_month(m){
  return month[m];
}

答案 3 :(得分:1)

怎么样:

function getMonth(mon){
   var monthNum = new Date(mon +" 1, 2012").getMonth()+1;
   return ("0" + monthNum).slice(-2);
}

Inspired from this SO post.

小提琴:http://jsfiddle.net/WFHWu/1/

答案 4 :(得分:0)

我会在这里使用查找(或者根据具体情况进行反查找)。

三元(?:是适当的直接替代品,因为它需要极大的嵌套量。

// The lookup, uses a dummy object (that will never match the indexOf)
// such that January is at index 1, etc.
var months = [{}, 'January', .., 'December'];

// This just returns a number, and expects the caller to format the number
// for display as appropriate. Returns 0 for an invalid month name.
function get_month(m) {
  var monthNumber = months.indexOf(m); // -1 if not found
  return monthNumber > 0 ? monthNumber : 0;
}

答案 5 :(得分:0)

对于您的特定任务,您还可以使用内置Date object

function get_month(m) {
    return new Date(m + " 1").getMonth() + 1;
}

但是,这将返回“1”而不是“01”,因此您必须编写一个在需要时添加第一个零的函数。

答案 6 :(得分:-1)

使用switch

var ret;
switch (m) {
    case 'January':
        ret = '01';
        break;
    case 'Febuary':
        ret = '02';
        break;

    ...

}

Documentation

答案 7 :(得分:-1)

我建议使用switch statement。你的另一个例子是三元运算符,甚至会更加混乱。