Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

javascript - 确定字符串是否在JavaScript中列表中(Determine if string is in list in JavaScript)

In SQL we can see if a string is in a list like so:(在SQL中,我们可以看到字符串是否在列表中,如下所示:)

Column IN ('a', 'b', 'c') What's a good way to do this in JavaScript?(在JavaScript中执行此操作的好方法是什么?) It's so clunky to do this:(这样做非常笨重:) if (expression1 || expression2 || str === 'a' || str === 'b' || str === 'c') { // do something } And I'm not sure about the performance or clarity of this:(而且我不确定这个的表现或清晰度:) if (expression1 || expression2 || {a:1, b:1, c:1}[str]) { // do something } Or one could use the switch function:(或者可以使用切换功能:) var str = 'a', flag = false; switch (str) { case 'a': case 'b': case 'c': flag = true; default: } if (expression1 || expression2 || flag) { // do something } But that is a horrible mess.(但这是一个可怕的混乱。) Any ideas?(有任何想法吗?) In this case, I have to use Internet Explorer 7 as it's for a corporate intranet page.(在这种情况下,我必须使用Internet Explorer 7作为企业内部网页面。) So ['a', 'b', 'c'].indexOf(str) !== -1 won't work natively without some syntax sugar.(所以['a', 'b', 'c'].indexOf(str) !== -1如果没有一些语法糖就无法原生工作。)   ask by ErikE translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can call indexOf :(你可以调用indexOf :)

if (['a', 'b', 'c'].indexOf(str) >= 0) { //do something }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...