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

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

问题描述

我有一个字符串数组和一个字符串。我想测试对数组值这个字符串并应用条件的结果 - 如果数组包含字符串做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,你可以用code在<一个填充工具这种方法href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf#Compatibility\"相对=nofollow>的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天全站免登陆