有没有更简单的方法来编写包含 10 个以上条件的 if 语句?
这是我的代码:
if (state == 'AZ' || state == 'CO' || state == 'DC' || state == 'IA' || state == 'LA' || state == 'MN' || state == 'NC' || state == 'ND' || state == 'NM' || state == 'NV' || state == 'OR' || state == 'SC' || state == 'TN' || state == 'VA' || state == 'WA' || state == 'WI' || state == 'WY') {}
是否有更简单的方法可以使用数组来编写此代码?这可行,但我希望它更干净!
Here is my code:
if (state == 'AZ' || state == 'CO' || state == 'DC' || state == 'IA' || state == 'LA' || state == 'MN' || state == 'NC' || state == 'ND' || state == 'NM' || state == 'NV' || state == 'OR' || state == 'SC' || state == 'TN' || state == 'VA' || state == 'WA' || state == 'WI' || state == 'WY') {}
Is there an easier way to write this using an array? This works, but I want it to be cleaner!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您可以使用对象:
编辑:
您还可以在字符串中查找字符串:(
这当然假设变量包含合理的内容,像
","
这样的值会给出误报。 )这恰好比大多数浏览器中的简单比较更快: http://jsperf.com/test-regexp-vs-obj/3
You can use an object:
Edit:
You could also look for the string in a string:
(This of course assumes that the variable contains something reasonable, a value like
","
would give a false positive.)This happens to be even faster than the plain comparisons in most browsers: http://jsperf.com/test-regexp-vs-obj/3
正则表达式:
Regular Expression:
如果您使用的是 jQuery:
如果您没有使用 jQuery,则需要自己的函数,例如 此问题的最佳答案。
If you're using jQuery:
If you're not you'll need your own function like the top answer to this question.
将所有可能性放入一个数组中,并使用 indexOf 来检查是否包含在其中。
示例:
或者添加 contains 并使用它:
Push all your possibilities into an array and use indexOf to check is contained in.
Example:
Or add contains and use it :
Hava 看看这个包含函数的 JavaScript 版本。
只需用您的状态代码填充一个数组,然后使用函数
http://css 进行检查-tricks.com/snippets/javascript/javascript-array-contains/
Hava at look at this javascript version of a contains function.
Simply populate an array with your state codes and check using the function
http://css-tricks.com/snippets/javascript/javascript-array-contains/
注意: IE
indexOf
不支持9. 如果您必须支持这些浏览器,您可以使用 jQuery:或 手动扩展数组原型。
NOTE:
indexOf
is not supported in IE < 9. If you have to support those browsers, you can either use jQuery:or manually extend the array prototype.
是实现这一目标的一种方法。
is one way to approach it.
如果您使用 CoffeeScript,它会生成 JavaScript 输出,您可以简单地编写
If you use CoffeeScript, which generates JavaScript output, you can simply write