if ( $.inArray('specialword', arr) > -1 ) {
// the value is in the array
}
775
您可以使用 for 循环:
var found = false;
for (var i = 0; i < categories.length && !found; i++) {
if (categories[i] === "specialword") {
found = true;
break;
}
}
4
我不喜欢 $.inArray(..) ,它是否容忍's the kind of ugly, jQuery-ish solution that most sane people wouldn' . 这是一个片段,为您的武器库添加了一个简单的 contains(str) 方法:
$.fn.contains = function (target) {
var result = null;
$(this).each(function (index, item) {
if (item === target) {
result = item;
}
});
return result ? result : false;
}
5 回答
你真的不需要jQuery .
要么
值得注意的是
array.indexOf(..)
是not supported in IE < 9,但是jQuery的indexOf(...)
函数甚至可以用于那些旧版本 .jQuery提供$.inArray:
请注意,inArray返回找到的元素的索引,因此
0
表示该元素是数组中的第一个元素 .-1
表示未找到该元素 .3.5年后编辑
$.inArray
实际上是支持它的浏览器中的Array.prototype.indexOf
的包装器(现在几乎全部都是这样),而在那些不支持的浏览器中提供垫片 . 它本质上相当于为Array.prototype
添加一个垫片,这是一种更惯用/ JSish的做事方式 . MDN提供such code . 这些天我会采用这个选项,而不是使用jQuery包装器 .3年后再编辑
天哪,6 . 5年?!
现代Javascript中最好的选择是
Array.prototype.includes
:没有比较,也没有混淆
-1
的结果 . 它做我们想要的:它返回true
或false
. 对于旧版浏览器,它是可填充的using the code at MDN .干得好:
此函数返回正整数(给定值的数组索引),如果在数组中找不到给定值,则返回
-1
.Live demo: http://jsfiddle.net/simevidas/5Gdfc/
您可能希望像这样使用它:
您可以使用
for
循环:我不喜欢
$.inArray(..)
,它是否容忍's the kind of ugly, jQuery-ish solution that most sane people wouldn' . 这是一个片段,为您的武器库添加了一个简单的contains(str)
方法:同样,您可以在扩展名中包装
$.inArray
: