如果一个字符串没有'It’不等于一堆东西

What is a better way of testing if a string doesn't equal a bunch of stuff?

本文关键字:不等于 It 一堆 一个 字符串 如果      更新时间:2023-09-26

现在我有:

if (breadCrumbArr[x] !== 'NEBC' && breadCrumbArr[x] !== 'station:|slot:' &&  breadCrumbArr[x] !== 'slot:' &&  breadCrumbArr[x] !== 'believe') {
    // more code
}

但我认为这可以做得更好。。。

制作一个数组并使用indexOf:

['NEBC', 'station:|slot:', 'slot:', 'believe'].indexOf(breadCrumbArr[x]) === -1

您可以使用switch语句:

switch(inputString){
  case "ignoreme1":
  case "ignoreme2":
  case "ignoreme3":
    break;
  default: 
    //Do your stuff
    break;
}

除了Blender的答案:如果你想跨浏览器,你也可以使用一个对象而不是数组:

var words = {
    'NEBC': true, 
    'station:|slot:': true, 
    'slot:': true, 
    'believe': true
};
if (!words[breadCrumbArr[x]]){
    //do stuff
}

它也更快,但也更难看,因为您必须为用作属性名称的每个字符串分配一个值(在本例中为true)。