這招在我看來,更優雅(使用數組和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