有人能告诉我如何检测 "specialword"
是否出现在数组中吗?例子:
categories: [
"specialword"
"word1"
"word2"
]
原文由 Cofey 发布,翻译遵循 CC BY-SA 4.0 许可协议
有人能告诉我如何检测 "specialword"
是否出现在数组中吗?例子:
categories: [
"specialword"
"word1"
"word2"
]
原文由 Cofey 发布,翻译遵循 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
结果。它做我们想要的:它返回 true
或 false
。对于旧版浏览器,它可以 使用 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 许可协议
10 回答11.6k 阅读
2 回答3.1k 阅读✓ 已解决
3 回答2.7k 阅读✓ 已解决
4 回答2.2k 阅读✓ 已解决
3 回答1.2k 阅读✓ 已解决
3 回答1.9k 阅读✓ 已解决
3 回答790 阅读✓ 已解决
你真的不需要 jQuery。
或者
值得注意的是 , IE < 9 不支持
array.indexOf(..)
,但 jQuery 的indexOf(...)
函数即使对于那些旧版本也可以工作。