可能重复:
在Javascript数组中测试值在JavaScript数组
中查找项目的最佳方法?
Javascript - array.contains(obj)
我通常在python中编程,但最近开始学习JavaScript.
在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!"
Run Code Online (Sandbox Code Playgroud)
但是我在Javascript中做了同样的事情.
如何在JavaScript中检查x是否在列表中?
Ash*_*nko 14
在javascript中你可以使用
if(list.indexOf(x) >= 0)
Run Code Online (Sandbox Code Playgroud)
PS:仅在现代浏览器中支持.
以更加传统的方式你可以这样做 -
//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;
};
Run Code Online (Sandbox Code Playgroud)
然后以这种方式调用此函数 -
if (myList.inArray('search term')) {
document.write("It's in the list!")
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42762 次 |
| 最近记录: |