javascript 如何在javascript中查找x是否等于数组中的任何值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18588865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find if x equals any value in an array in javascript
提问by user2468491
I currently have an if statement like this:
我目前有一个这样的 if 语句:
if (x==a||x==b||x==c||x==d||x==e) {
alert('Hello World!')
};
How can I instead test if x
equals any value in an array such as [a,b,c,d,e]
?
我该如何测试是否x
等于数组中的任何值,例如[a,b,c,d,e]
?
Thank you!
谢谢!
回答by Ingo Bürk
You can use
您可以使用
if([a,b,c,d,e].indexOf(x) !== -1) {
// ...
}
回答by Shivam
You can use the following code:
您可以使用以下代码:
<script>
var arr = [ 4, "Pete", 8, "John" ];
var $spans = $("span");
$spans.eq(0).text(jQuery.inArray("John", arr));
$spans.eq(1).text(jQuery.inArray(4, arr));
$spans.eq(2).text(jQuery.inArray("Karl", arr));
$spans.eq(3).text(jQuery.inArray("Pete", arr, 2));
</script>
Read this link for more information about it
Hope this helps you.
希望这对你有帮助。
回答by joao
check out jquery function inArray(): http://api.jquery.com/jQuery.inArray/
查看 jquery 函数 inArray():http://api.jquery.com/jQuery.inArray/
回答by Niet the Dark Absol
Try this helper function:
试试这个辅助功能:
function in_array(needle,haystack) {
if( haystack.indexOf) return haystack.indexOf(needle) > -1;
for( var i=0, l=haystack.length, i<l; i++) if(haystack[i] == needle) return true;
return false;
}
This makes use of the built-in indexOf
if available, otherwise it iterates manuatlly.
indexOf
如果可用,这将使用内置,否则它会手动迭代。