如何检查字符串数组是否包含 JavaScript 中的一个字符串? [英] How to check if a string array contains one string in JavaScript?

查看:40
本文介绍了如何检查字符串数组是否包含 JavaScript 中的一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串数组和一个字符串.我想针对数组值测试这个字符串并应用一个条件结果 - 如果数组包含字符串 do "A",否则执行 "B".

I have a string array and one string. I'd like to test this string against the array values and apply a condition the result - if the array contains the string do "A", else do "B".

我该怎么做?

推荐答案

有一个 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.

这篇关于如何检查字符串数组是否包含 JavaScript 中的一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆