如何查找数组是否在JavaScript / jQuery中包含特定字符串?

2022-08-29 22:33:08

有人可以告诉我如何检测数组中是否出现吗?例:"specialword"

categories: [
    "specialword"
    "word1"
    "word2"
]

答案 1

你真的不需要jQuery。

var myarr = ["I", "like", "turtles"];
var arraycontainsturtles = (myarr.indexOf("turtles") > -1);

提示:indexOf 返回一个数字,表示指定搜索值首次出现的位置,如果从未出现过,则返回 -1

function arrayContains(needle, arrhaystack)
{
    return (arrhaystack.indexOf(needle) > -1);
}

值得注意的是,IE < 9不支持,但jQuery的功能即使适用于那些较旧的版本。array.indexOf(..)indexOf(...)


答案 2

jQuery 提供 $.inArray

请注意,inArray 返回找到的元素的索引,因此指示该元素是数组中的第一个元素。 表示未找到该元素。0-1

var categoriesPresent = ['word', 'word', 'specialword', 'word'];
var categoriesNotPresent = ['word', 'word', 'word'];

var foundPresent = $.inArray('specialword', categoriesPresent) > -1;
var foundNotPresent = $.inArray('specialword', categoriesNotPresent) > -1;

console.log(foundPresent, foundNotPresent); // true false
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

3.5年后编辑

$.inArray在支持它的浏览器中(现在几乎所有浏览器)实际上是一个包装器,同时在那些不支持它的浏览器中提供填充码。它本质上等同于添加一个填充程序,这是一种更惯用/JSish的做事方式。MDN提供这样的代码。这些天我会选择这个选项,而不是使用jQuery包装器。Array.prototype.indexOfArray.prototype

var categoriesPresent = ['word', 'word', 'specialword', 'word'];
var categoriesNotPresent = ['word', 'word', 'word'];

var foundPresent = categoriesPresent.indexOf('specialword') > -1;
var foundNotPresent = categoriesNotPresent.indexOf('specialword') > -1;

console.log(foundPresent, foundNotPresent); // true false

3年后再编辑

天哪,6.5年?!

在现代Javascript中,最好的选择是:Array.prototype.includes

var found = categories.includes('specialword');

没有比较,也没有令人困惑的结果。它做我们想要的:它返回或.对于较旧的浏览器,它可以使用MDN上的代码进行polyfill。-1truefalse

var categoriesPresent = ['word', 'word', 'specialword', 'word'];
var categoriesNotPresent = ['word', 'word', 'word'];

var foundPresent = categoriesPresent.includes('specialword');
var foundNotPresent = categoriesNotPresent.includes('specialword');

console.log(foundPresent, foundNotPresent); // true false