javascript,jQuery - 检查数组中是否存在值

时间:2012-08-02 14:18:33

标签: javascript jquery arrays jvectormap

是否有更好的方法可以检查多个项目与if语句中的变量匹配

我有3个if语句,我需要查看一个项是否与名为code的数组/变量匹配。有很多项要与代码数组/变量进行比较,所以我不得不用|来复制每一个它们之间。是否有更有效的方法或者我可以使用一次数组来检查代码是否等于数组中的任何项目?

这就是我所拥有的

onLabelShow: function(event, label, code){
        if (code == "US-AL" | code == "US-AZ" | code == "US-CA" | code == "US-CT" | code == "US-FL" | code == "US-HI" | code == "US-ID" | code == "US-IL" | code == "US-IA" | code == "US-LA" | code == "US-ME" | code == "US-MD" | code == "US-MA" | code == "US-MO" | code == "US-NE" | code == "US-NV" | code == "US-NJ" | code == "US-NM" | code == "US-NY" | code == "US-OH" | code == "US-OK" | code == "US-OR" | code == "US-PA" | code == "US-TN" | code == "US-UT" | code == "US-VA" | code == "US-CA" | code == "US-WA" | code == "US-NC" ) {
            //do nothing
        }
        else if (code) { //if a state is not specified in var stateRedirects then prevent default
            event.preventDefault();
        }                   
    },      
    onRegionOver: function(event, code){
        if (code == "US-AL" | code == "US-AZ" | code == "US-CA" | code == "US-CT" | code == "US-FL" | code == "US-HI" | code == "US-ID" | code == "US-IL" | code == "US-IA" | code == "US-LA" | code == "US-ME" | code == "US-MD" | code == "US-MA" | code == "US-MO" | code == "US-NE" | code == "US-NV" | code == "US-NJ" | code == "US-NM" | code == "US-NY" | code == "US-OH" | code == "US-OK" | code == "US-OR" | code == "US-PA" | code == "US-TN" | code == "US-UT" | code == "US-VA" | code == "US-CA" | code == "US-WA" | code == "US-NC" ) {
            //do nothing
        }
        else if (code) { //if a state is not specified in var stateRedirects then prevent default
            event.preventDefault();
        }                   
    },
    onRegionClick: function (event, code) {
        if (code == "US-AL" | code == "US-AZ" | code == "US-CA" | code == "US-CT" | code == "US-FL" | code == "US-HI" | code == "US-ID" | code == "US-IL" | code == "US-IA" | code == "US-LA" | code == "US-ME" | code == "US-MD" | code == "US-MA" | code == "US-MO" | code == "US-NE" | code == "US-NV" | code == "US-NJ" | code == "US-NM" | code == "US-NY" | code == "US-OH" | code == "US-OK" | code == "US-OR" | code == "US-PA" | code == "US-TN" | code == "US-UT" | code == "US-VA" | code == "US-CA" | code == "US-WA" | code == "US-NC" ) {
            window.location = '/' + code;
        }
        else if (code) { //if a state is not specified in var stateRedirects then prevent default
            //event.preventDefault();
        }   

    }   

任何帮助,示例或代码将不胜感激!我已经尝试过为每个人做,但我认为我不知道如何使用数组。

2 个答案:

答案 0 :(得分:45)

var codes = ["US-AL", "US-AZ", ... ];


if($.inArray(code, codes) > -1){
    //do something    
}

<强>更新 结合@Deestan的建议,这可以重写为..

function isValidCode(code){
    return ($.inArray(code, codes) > -1);
}

答案 1 :(得分:15)

Yep

array.indexOf(searchElement[, fromIndex])