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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12623272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:52:19  来源:igfitidea点击:

How to check if a string array contains one string in JavaScript?

javascriptarraysstringtesting

提问by gtludwig

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".

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

How can I do that?

我怎样才能做到这一点?

回答by James Allardice

There is an indexOfmethod 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:

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

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

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

如果您需要支持旧的 IE 浏览器,您可以使用MDN 文章中的代码 polyfill 该方法。

回答by fableal

You can use the indexOfmethod and "extend" the Array class with the method containslike this:

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

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

with the following results:

结果如下:

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

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

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

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

回答by FixMaker

var stringArray = ["String1", "String2", "String3"];

return (stringArray.indexOf(searchStr) > -1)

回答by eridanix

Create this function prototype:

创建此函数原型:

Array.prototype.contains = function ( needle ) {
   for (i in this) {
      if (this[i] == needle) return true;
   }
   return false;
}

and then you can use following code to search in array x

然后您可以使用以下代码在数组 x 中搜索

if (x.contains('searchedString')) {
    // do a
}
else
{
      // do b
}

回答by ollie

This will do it for you:

这将为您做到:

function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(haystack[i] == needle)
            return true;
    }
    return false;
}

I found it in Stack Overflow question JavaScript equivalent of PHP's in_array().

我在 Stack Overflow 问题JavaScript 中找到了它,相当于 PHP 的 in_array()