如何在javascript中将多个if条件减少为单个缩短的条件

时间:2013-11-14 18:50:23

标签: javascript jquery

有多个if条件用字符串KAP替换字符串:

var nameList = $('#name').text();

if(nameList.indexOf('SAM') > -1){
    var newName = nameList.replace(/SAM/g, 'KAP');
    $('#name').html(newName);
}

if(nameList.indexOf('PAT') > -1){
    var newName = nameList.replace(/PAT/g, 'KAP');
    $('#name').html(newName);
}

如果我们在数组中已经存在新名称,如何使用jquery / javascript将上述两个内容压缩为单个if条件

var nameArray = ['SAM','PAT','DAB'];

如果在nameList中找到上述任何一项,则不会检查其他条件。

4 个答案:

答案 0 :(得分:1)

var nameList = $('#name').text();

var nameArray = ['SAM','PAT','DAB'];
nameArray.some(function(name) {
    if (!!~nameList.indexOf(name)) {
        nameList.replace(new RegExp(name, 'gi'), 'KAP');
        return true;
    }
    return false;
});

Array.some方法遍历数组的元素,直到函数返回true。 结帐Mozilla Developers documentation

!!〜是操作数的组合,只有-1假。

答案 1 :(得分:0)

最基本的我建议:

var nameArray = ['SAM','PAT','DAB'],
    reg = new RegExp('(' + nameArray.join('|') + ')', 'i'),
if (reg.test(nameList)) {
    // one of those names was found
}
else {
    // none of those names were found
}

Simplified JS Fiddle demo

答案 2 :(得分:0)

在这里,你去:

JS小提琴: http://jsfiddle.net/2F4dG/2/

<强> HTML

<div id="name">Hi my name is Sam. Sam is cool.</div>

<强> CODE

$(function(){
    var nameList = $('#name').text()

    var nameArray = ['SAM','PAT','DAB'];

    //loop through all possible names
    for(var i=0;i<nameArray.length;i++){
        if(nameList.toUpperCase().indexOf(nameArray[i])!=-1){
            //new regex out of name we are replacing...
            var re = new RegExp(nameArray[i],"gi");
            //replacae all matches
            var newName = nameList.replace(re,"KAP");
            //set new name
            $('#name').html(newName);
            //exit loop we found our match...
            break;
        }
    }
});

<强>输出

Hi my name is KAP. KAP is cool.

答案 3 :(得分:0)

您不需要任何if / else语句 - 您只需使用正则表达式

var nameArray = ['SAM','PAT','DAB'];// your list of words
var nameList = $('#name').text();// your string to check
var reg = new RegExp(nameArray.join('|'),"g");// create the regex object - reg == /SAM|PAT|DAB/g
$('#name').html(nameList.replace(reg,'KAP'));

FIDDLE