谁能告诉我如何检测"specialword"
是否出现在一个数组中?例子。
categories: [
"specialword"
"word1"
"word2"
]
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>
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年?!</sub>。
在现代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
给你。
$.inArray('specialword', arr)
该函数返回一个正整数(给定值的数组索引),如果在数组中没有找到给定值,则返回`-1'。
实时演示:
你可能想这样使用它。
if ( $.inArray('specialword', arr) > -1 ) {
// the value is in the array
}