如果在x中的Javascript

Cod*_*ahk 33 javascript

可能重复:
在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是否在列表中?

Que*_*tin 36

使用JS 1.6中引入的indexOf.您需要使用该页面上"兼容性"下列出的代码来添加对未实现该JS版本的浏览器的支持.

JavaScript确实有一个in运算符,但它测试的是而不是值.


Ash*_*nko 14

在javascript中你可以使用

if(list.indexOf(x) >= 0)
Run Code Online (Sandbox Code Playgroud)

PS:仅在现代浏览器中支持.


Viv*_*vek 6

以更加传统的方式你可以这样做 -

//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)