是否更容易编写超过10个条件的if语句?

时间:2011-08-25 21:00:37

标签: javascript arrays if-statement

这是我的代码:

if (state == 'AZ' || state == 'CO' || state == 'DC' || state == 'IA' || state == 'LA' || state == 'MN' || state == 'NC' || state == 'ND' || state == 'NM' || state == 'NV' || state == 'OR' || state == 'SC' || state == 'TN' || state == 'VA' || state == 'WA' || state == 'WI' || state == 'WY') {}

使用数组是否有更简单的方法来编写它?这有效,但我希望它更清洁!

8 个答案:

答案 0 :(得分:4)

您可以使用对象:

if ({AZ:1,CO:1,DC:1,IA:1,LA:1,MN:1,NC:1,ND:1,NM:1,NV:1,OR:1,SC:1,TN:1,VA:1,WA:1,WI:1,WY:1}[state] == 1) {

编辑:

您还可以在字符串中查找字符串:

if ("AZ,CO,DC,IA,LA,MN,NC,ND,NM,NV,OR,SC,TN,VA,WA,WI,WY".indexOf(state) != -1) {

(当然这假设变量包含一些合理的东西,像","这样的值会产生误报。)

这恰好比大多数浏览器中的简单比较更快:http://jsperf.com/test-regexp-vs-obj/3

答案 1 :(得分:3)

正则表达式:

if(state.match(/^(AZ|CO|DC|IA|LA|MN|NC|ND|NM|NV|OR|SC|TN|VA|WA|WI|WY)$/)){
    //do whatever
}

答案 2 :(得分:2)

将所有可能性推送到数组中,并使用indexOf进行检查。

示例:

if(['NA', 'NB', 'NC'].indexOf(state) > -1)
{
    // true
}

或添加包含并使用它:

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
}

if(['NA', 'NB', 'NC'].contains(state))
{
    // true
}

答案 3 :(得分:2)

如果你正在使用jQuery:

var states = ['AZ' ,'CO' ,'DC' ,'IA' ,'LA' ,'MN' ,'NC' ,'ND' ,'NM' ,'NV' ,'OR' ,'SC' ,'TN' ,'VA' ,'WA' ,'WI' ,'WY'];
if($.inArray('AZ',states)>=0){
    console.log('Hurrah');
}

如果你不是,你将需要自己的功能,如this question的最佳答案。

答案 4 :(得分:1)

if ( ['AZ', 'CO', 'DC', 'And so on'].indexOf(state) != -1 ) {
    // do something
}

注意:<&strong> indexOf不支持IE&lt; 9.如果你必须支持这些浏览器,你可以使用jQuery:

if ( $.inArray(state, 'AZ', 'CO', 'DC', 'And so on') != -1 ) {
    // do something
}

manually extend the array prototype

答案 5 :(得分:1)

Hava看看这个包含函数的javascript版本。 只需使用州代码填充数组并使用函数

进行检查

http://css-tricks.com/snippets/javascript/javascript-array-contains/

答案 6 :(得分:0)

var states=new Array("AZ", "CO", ...);
for (s in states) {
  if (state == s) {
    // do something
    break;
  }
}

是接近它的一种方式。

答案 7 :(得分:0)

如果使用生成JavaScript输出的CoffeeScript,则只需编写

即可
if state in ['AZ', 'CO', 'DC', 'IA', 'LA', 'MN', 'NC', 'ND', 'NM', 'NV', 'OR', 'SC', 'TN', 'VA', 'WA', 'WI', 'WY']
    ...