Javascript: Comparing SINGLE Value Against MULTIPLE Values with OR Operands [duplicate]

点点圈 提交于 2019-12-01 08:34:49
Bergi

You could use a variable and multiple comparison, but that's still lengthy:

var text = item[i].innerText;
if (text === 'Argentina' | text === 'Australia' | text === 'Brazil' | text === 'Canada' | text === 'China' | text === 'Colombia' | text === 'France' | text === 'Germany' | text === 'Indonesia' | text === 'India' | text === 'Italy' | text === 'Japan' | text === 'Malaysia' | text === 'Mexico' | text === 'Philippines' | text === 'Russia' | text === 'South Africa' | text === 'Sweden' | text === 'Switzerland' | text === 'United Kingdom' | text === 'USA')

Or you could just use an array and check if the string is contained in it.

var matches = ['Argentina','Australia','Brazil','Canada','China','Colombia','France','Germany','Indonesia','India','Italy','Japan','Malaysia','Mexico','Philippines','Russia','South Africa','Sweden','Switzerland','United Kingdom','USA'];
if (~ matches.indexOf(item[i].innerText) …

Yet, for the complicated != -1 comparison and the lack of native indexOf in older IEs, people tend to use regexes:

var regex = /Argentina|Australia|Brazil|Canada|China|Colombia|France|Germany|Indonesia|India|Italy|Japan|Malaysia|Mexico|Philippines|Russia|South Africa|Sweden|Switzerland|United Kingdom|USA/
if (regex.test(item[i].innerText)) …
var options = ['Argentina', 'Australia', 'Brazil', 'Canada', ...];
if (options.indexOf(item[i].innerText) !== -1){
  // item[i] was found in options
}

Something like that? use Array.indexOf (Unless I've mis-read the question? In which case post a comment and I'll do my best to re-work my answer)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!