这招在我看来,更优雅(使用数组和indexOf ):
var conflicts = ['CONFLICT-GROUP-GENERAL',
'CONFLICT-USER-GENERAL',
'CONFLICT-FORM-GENERAL',
'CONFLICT-PROJECT-GENERAL',
'CONFLICT-TEMPLATE-GENERAL'];
if (conflicts.indexOf(err.code) !== -1) {
doSomething();
}
如果您正在使用ES7那么你可以使用includes()而不是indexOf
。这将是更多的“表现”:
var conflicts = ['CONFLICT-GROUP-GENERAL',
'CONFLICT-USER-GENERAL',
'CONFLICT-FORM-GENERAL',
'CONFLICT-PROJECT-GENERAL',
'CONFLICT-TEMPLATE-GENERAL'];
if (conflicts.inclues(err.code)) {
doSomething();
}
注意includes()
不会被所有浏览器都支载。
编辑:
另一种替代方法:使用switch。这种方式:
switch (err.code) {
case 'CONFLICT-GROUP-GENERAL',:
case 'CONFLICT-USER-GENERAL',:
case 'CONFLICT-FORM-GENERAL',:
case 'CONFLICT-PROJECT-GENERAL',:
case 'CONFLICT-TEMPLATE-GENERAL':
doSomething();
break;
}
当err.code
等于在每一特定case
串中的一个上面的代码将执行doSomething()
功能。
正确的解决方案取决于“{}”之间的内容。 –
我会使用[switch](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch)。 – James