且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查字符串数组是否包含 JavaScript 中的一个字符串?

更新时间:2022-11-17 14:41:27

有一个 indexOf 方法,所有数组(Internet Explorer 8 及以下版本除外)都将返回数组中元素的索引,如果不是,则返回 -1在数组中:

There is an indexOf method that all arrays have (except Internet Explorer 8 and below) that will return the index of an element in the array, or -1 if it's not in the array:

if (yourArray.indexOf("someString") > -1) {
    //In the array!
} else {
    //Not in the array
}

如果你需要支持旧的IE浏览器,你可以使用MDN 文章.

If you need to support old IE browsers, you can polyfill this method using the code in the MDN article.