Javascript 如果在 x
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6356122/
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
Javascript if in x
提问by Codahk
Possible Duplicates:
Test for value in Javascript Array
Best way to find an item in a JavaScript Array ?
Javascript - array.contains(obj)
可能的重复项:
测试 Javascript 数组中的值 在 JavaScript 数组
中查找项目的最佳方法?
Javascript - array.contains(obj)
I usually program in python but have recently started to learn JavaScript.
我通常用 python 编程,但最近开始学习 JavaScript。
In python this is a perfectly valid if statement:
在 python 中,这是一个完全有效的 if 语句:
list = [1,2,3,4]
x = 3
if x in list:
print "It's in the list!"
else:
print "It's not in the list!"
but I have had poblems doing the same thing in Javascript.
但是我在 Javascript 中遇到过同样的事情。
How do you check if x is in list y in JavaScript?
在 JavaScript 中如何检查 x 是否在列表 y 中?
回答by Quentin
Use indexOfwhich was introduced in JS 1.6. You will need to use the code listed under "Compatibility" on that page to add support for browsers which don't implement that version of JS.
使用JS 1.6 中引入的indexOf。您将需要使用该页面上“兼容性”下列出的代码来添加对未实现该版本 JS 的浏览器的支持。
JavaScript does have an in
operator, but it tests for keysand not values.
JavaScript 确实有一个in
运算符,但它测试的是键而不是值。
回答by Ash Burlaczenko
In javascript you can use
在javascript中你可以使用
if(list.indexOf(x) >= 0)
P.S.: Only supported in modern browsers.
PS:仅在现代浏览器中支持。
回答by Vivek
in more genric way you can do like this-
以更通用的方式,您可以这样做-
//create a custopm function which will check value is in list or not
Array.prototype.inArray = function (value)
// Returns true if the passed value is found in the
// array. Returns false if it is not.
{
var i;
for (i=0; i < this.length; i++) {
// Matches identical (===), not just similar (==).
if (this[i] === value) {
return true;
}
}
return false;
};
then call this function in this way-
然后以这种方式调用此函数-
if (myList.inArray('search term')) {
document.write("It's in the list!")
}