JavaScript中的if条件语句

39

2
https://dev59.com/E3VC5IYBdhLWcg3wnCj6 - Anders Lindahl
3个回答

40

使用在JS 1.6引入的indexOf方法。对于那些不支持该版本JS的浏览器,您需要使用该页面“兼容性”下列出的代码。

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

p.s.原始回答来源于2011年,现在所有正在使用的浏览器都支持。 https://caniuse.com/?search=indexof


20

仅适用于现代浏览器。 - T.J. Crowder
@T.J - 理解了。哪些浏览器不支持这个? - Ash Burlaczenko
我不知道完整的列表,但是它在IE8及以下版本中缺失(没错,真的)。微软最终在IE9中加入了它。我认为其他主流浏览器已经有这个功能好几年了,但对于一些移动浏览器(如Blackberry等)就不太清楚了。你可以在这里检查:http://jsbin.com/uzama4/3. - T.J. Crowder

5
以更通用的方式,您可以这样做 -
//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;
};

然后以这种方式调用该函数 -
if (myList.inArray('search term')) {
     document.write("It's in the list!")
}  

1
为什么不直接使用Array.includes呢? - netishix
如果 (y 在 list 中 === false) 则 console.log(${y} 不存在于 [${list}]);否则 console.log(${y} 存在于 [${list}]); - Emmanuel Onah
if (list.includes(x)) console.log("它在列表中!"); else console.log("它不在列表中!"); - Emmanuel Onah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接