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

新手上路,请多包涵

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

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

原文由 Cofey 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 999
2 个回答

你真的不需要 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 不支持 array.indexOf(..) ,但 jQuery 的 indexOf(...) 函数即使对于那些旧版本也可以工作。

原文由 James 发布,翻译遵循 CC BY-SA 4.0 许可协议

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 实际上是 Array.prototype.indexOf 在支持它的浏览器(现在几乎所有浏览器)中的包装器,同时在那些不支持它的浏览器中提供垫片。它本质上等同于向 Array.prototype 添加垫片,这是一种更惯用/JSish 的做事方式。 MDN 提供了 这样的代码。这些天我会选择这个选项,而不是使用 jQuery 包装器。

 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');

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

 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

原文由 lonesomeday 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题