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

82 浏览
0 Comments

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

This question already has answers here:

如何在JavaScript中检查数组是否包含某个值?

我有一个字符串数组和一个字符串。我想将该字符串与数组值进行比较,并根据结果应用条件 - 如果数组包含该字符串,则执行“A”,否则执行“B”。

我该如何实现?

admin 更改状态以发布 2023年5月24日
0
0 Comments

您可以使用indexOf方法并“扩展”Array类以使用contains方法,方法如下:

Array.prototype.contains = function(element){
    return this.indexOf(element) > -1;
};

使用以下结果:

["A", "B", "C"].contains("A") 等于 true

["A", "B", "C"].contains("D") 等于 false

0
0 Comments

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

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

如果您需要支持旧的IE浏览器,您可以使用MDN文章中的代码来模拟这个方法。

0