本文翻译自:Determine whether an array contains a value [duplicate]
I need to determine if a value exists in an array. 我需要确定数组中是否存在值。
I am using the following function: 我正在使用以下功能:
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
The above function always returns false. 上面的函数总是返回false。
The array values and the function call is as below: 数组值和函数调用如下:
arrValues = ["Sam","Great", "Sample", "High"]
alert(arrValues.contains("Sam"));
#1楼
参考:https://stackoom.com/question/4xNf/确定数组是否包含值-重复
#2楼
var contains = function(needle) {
// Per spec, the way to identify NaN is that it is not equal to itself
var findNaN = needle !== needle;
var indexOf;
if(!findNaN && typeof Array.prototype.indexOf === 'function') {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(needle) {
var i = -1, index = -1;
for(i = 0; i < this.length; i++) {
var item = this[i];
if((findNaN && item !== item) || item === needle) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle) > -1;
};
You can use it like this: 您可以像这样使用它:
var myArray = [0,1,2],
needle = 1,
index = contains.call(myArray, needle); // true
CodePen validation/usage CodePen验证/使用
#3楼
This is generally what the indexOf() method is for. 通常,这就是indexOf()方法的用途。 You would say: 你会说:
return arrValues.indexOf('Sam') > -1
#4楼
Given the implementation of indexOf for IE (as described by eyelidlessness): 给定IE的indexOf的实现(如失明所描述):
Array.prototype.contains = function(obj) {
return this.indexOf(obj) > -1;
};
#5楼
You can use _.indexOf method or if you don't want to include whole Underscore.js library in your app, you can have a look how they did it and extract necessary code. 您可以使用_.indexOf方法,或者如果您不想在应用程序中包含整个Underscore.js库,则可以查看它们是如何做到的并提取必要的代码。
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i = 0, l = array.length;
if (isSorted) {
if (typeof isSorted == 'number') {
i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
} else {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
}
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
for (; i < l; i++) if (array[i] === item) return i;
return -1;
};
#6楼
jQuery has a utility function for this: jQuery为此具有实用程序功能:
$.inArray(value, array)
Returns index of value
in array
. 返回array
的value
索引。 Returns -1
if array
does not contain value
. 如果array
不包含value
则返回-1
。
See also How do I check if an array includes an object in JavaScript? 另请参阅如何检查数组是否在JavaScript中包含对象?