This question already has an answer here:
这个问题已经有了答案:
- How do I check if an array includes an object in JavaScript? 40 answers
- 如何检查数组是否包含JavaScript中的对象?40的答案
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"));
18 个解决方案
#1
940
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验证/使用
#2
916
jQuery has a utility function for this:
jQuery为此提供了一个实用函数:
$.inArray(value, array)
Returns index of value
in array
. Returns -1
if array
does not contain value
.
返回数组中值的索引。如果数组不包含值,返回-1。
See also How do I check if an array includes an object in JavaScript?
请参见如何检查数组是否包含JavaScript中的对象?
#3
720
This is generally what the indexOf() method is for. You would say:
这通常是indexOf()方法的用途。你会说:
return arrValues.indexOf('Sam') > -1
#4
228
Array.prototype.includes()
In ES2016, there is Array.prototype.includes()
.
在ES2016中,有array .prototype.include()。
The
includes()
method determines whether an array includes a certain element, returningtrue
orfalse
as appropriate.方法确定数组是否包含某个元素,并根据需要返回true或false。
Example
["Sam", "Great", "Sample", "High"].includes("Sam"); // true
Support
According to kangax and MDN, the following platforms are supported:
根据kangax和MDN,支持以下平台:
- Chrome 47
- Chrome 47
- Edge 14
- 边缘14
- Firefox 43
- Firefox 43
- Opera 34
- 歌剧34
- Safari 9
- Safari 9
- Node 6
- 节点6
Support can be expanded using Babel (using babel-polyfill
) or core-js
. MDN also provides a polyfill:
可以使用Babel(使用Babel -polyfill)或core-js扩展支持。MDN还提供一种polyfill:
if (![].includes) {
Array.prototype.includes = function(searchElement /*, fromIndex*/ ) {
'use strict';
var O = Object(this);
var len = parseInt(O.length) || 0;
if (len === 0) {
return false;
}
var n = parseInt(arguments[1]) || 0;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {k = 0;}
}
var currentElement;
while (k < len) {
currentElement = O[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)) {
return true;
}
k++;
}
return false;
};
}
#5
115
It's almost always safer to use a library like lodash simply because of all the issues with cross-browser compatibilities and efficiency.
使用lodash这样的库几乎总是更安全,因为存在跨浏览器兼容性和效率问题。
Efficiency because you can be guaranteed that at any given time, a hugely popular library like underscore will have the most efficient method of accomplishing a utility function like this.
效率,因为您可以保证,在任何给定的时间,一个非常流行的库(如下划线)将具有完成这样一个实用函数的最有效方法。
_.includes([1, 2, 3], 3); // returns true
If you're concerned about the bulk that's being added to your application by including the whole library, know that you can include functionality separately:
如果您担心通过包含整个库添加到应用程序中的大量内容,那么要知道您可以分别包含以下功能:
var includes = require('lodash/collections/includes');
NOTICE: With older versions of lodash, this was _.contains()
rather than _.includes()
.
注意:对于旧版本的lodash,这是_.contains()而不是_.include()。
#6
46
tl;dr
博士tl;
function includes(k) {
for(var i=0; i < this.length; i++){
if( this[i] === k || ( this[i] !== this[i] && k !== k ) ){
return true;
}
}
return false;
}
Example
例子
function includes(k) {
for(var i=0; i < this.length; i++){
if( this[i] === k || ( this[i] !== this[i] && k !== k ) ){
return true;
}
}
return false;
}
function log(msg){
$('#out').append('<div>' + msg + '</div>');
}
var arr = [1, "2", NaN, true];
arr.includes = includes;
log('var arr = [1, "2", NaN, true];');
log('<br/>');
log('arr.includes(1): ' + arr.includes(1));
log('arr.includes(2): ' + arr.includes(2));
log('arr.includes("2"): ' + arr.includes("2"));
log('arr.includes(NaN): ' + arr.includes(NaN));
log('arr.includes(true): ' + arr.includes(true));
log('arr.includes(false): ' + arr.includes(false));
#out{
font-family:monospace;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=out></div>
Longer Answer
再回答
I know this question isn't really about whether or not to extend built-in objects, but the attempt of the OP and the comments on this answer highlight that debate. My comment from Feb 12, '13 cites an article that outlines this debate really well, however that link broke and I can't edit the original comment because too much time has passed, so I include it here.
我知道这个问题并不是关于是否扩展内置对象,而是OP的尝试和对这个答案的评论突出了这个争论。13年2月12日我的评论引用了一篇文章,很好地概括了这场辩论,但是链接坏了,我不能编辑原来的评论,因为时间太长了,所以我把它写在这里。
If you're looking to extend the built-in Array
object with a contains
method, probably the best and most responsible way to do this would be to use this polyfill from MDN. (See also this section of the MDN article on Prototypical inheritance, which explains that "The only good reason for extending a built-in prototype is to backport the features of newer JavaScript engines; for example Array.forEach, etc.")
如果您希望使用contains方法扩展内置数组对象,那么最好和最负责任的方法可能是使用MDN中的这个polyfill。(还请参阅MDN关于原型继承的文章的这一节,其中解释了“扩展内置原型的唯一好理由是支持更新的JavaScript引擎的特性;例如数组。forEach等。”)
if (!Array.prototype.includes) {
Array.prototype.includes = function(searchElement /*, fromIndex*/ ) {
'use strict';
var O = Object(this);
var len = parseInt(O.length) || 0;
if (len === 0) {
return false;
}
var n = parseInt(arguments[1]) || 0;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {k = 0;}
}
var currentElement;
while (k < len) {
currentElement = O[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)) {
return true;
}
k++;
}
return false;
};
}
Don't want strict equality, or want to choose?
不想要严格的平等,还是想要选择?
function includes(k, strict) {
strict = strict !== false; // default is true
// strict = !!strict; // default is false
for(var i=0; i < this.length; i++){
if( (this[i] === k && strict) ||
(this[i] == k && !strict) ||
(this[i] !== this[i] && k !== k)
) {
return true;
}
}
return false;
}
#7
30
Since ECMAScript6, one can use Set
:
由于ECMAScript6,可以使用Set:
var myArray = ['A', 'B', 'C'];
var mySet = new Set(myArray);
var hasB = mySet.has('B'); // true
var hasZ = mySet.has('Z'); // false
#8
17
My little contribution:
我的小贡献:
function isInArray(array, search)
{
return array.indexOf(search) >= 0;
}
//usage
if(isInArray(my_array, "my_value"))
{
//...
}
#9
16
Given the implementation of indexOf for IE (as described by eyelidlessness):
给定IE的indexOf的实现(用无眼睑描述):
Array.prototype.contains = function(obj) {
return this.indexOf(obj) > -1;
};
#10
15
If you have access to ECMA 5 you can use the some method.
如果您可以访问ECMA 5,您可以使用some方法。
MDN一些方法链接
arrValues = ["Sam","Great", "Sample", "High"];
function namePresent(name){
return name === this.toString();
}
// Note:
// namePresent requires .toString() method to coerce primitive value
// i.e. String {0: "S", 1: "a", 2: "m", length: 3, [[PrimitiveValue]]: "Sam"}
// into
// "Sam"
arrValues.some(namePresent, 'Sam');
=> true;
If you have access to ECMA 6 you can use the includes method.
如果您能够访问ECMA 6,您可以使用include方法。
MDN包括方法链接
arrValues = ["Sam","Great", "Sample", "High"];
arrValues.includes('Sam');
=> true;
#11
11
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.
您可以使用_。索引方法或如果您不想包含整个下划线。在你的app中,你可以看看他们是怎么做的,并提取出必要的代码。
_.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;
};
#12
9
Another option would be to use Array.some
(if available) in the following way:
另一种选择是使用数组。一些(如有)以下列方式:
Array.prototype.contains = function(obj) {
return this.some( function(e){ return e === obj } );
}
The anonymous function passed to Array.some
will return true
if and only if there is an element in the array that is identical to obj
. Absent such an element, the function will not return true
for any of the elements of the array, so Array.some
will return false
as well.
传递给数组的匿名函数。当且仅当数组中有与obj相同的元素时,有些将返回true。如果没有这样的元素,函数将不会返回对数组元素的任何元素。有些也会返回false。
#13
6
Wow, there are a lot of great answers to this question.
哇,这个问题有很多很好的答案。
I didn't see one that takes a reduce
approach so I'll add it in:
我没见过有什么方法可以用reduce方法,所以我把它加进来:
var searchForValue = 'pig';
var valueIsInArray = ['horse', 'cat', 'dog'].reduce(function(previous, current){
return previous || searchForValue === current ? true : false;
}, false);
console.log('The value "' + searchForValue + '" is in the array: ' + valueIsInArray);
Here's a fiddle of it in action.
这里有一个小提琴在演奏。
#14
4
The answer provided didn't work for me, but it gave me an idea:
答案并不适合我,但它给了我一个想法:
Array.prototype.contains = function(obj)
{
return (this.join(',')).indexOf(obj) > -1;
}
It isn't perfect because items that are the same beyond the groupings could end up matching. Such as my example
它并不完美,因为超出分组的相同项最终可能会匹配。比如我的例子
var c=[];
var d=[];
function a()
{
var e = '1';
var f = '2';
c[0] = ['1','1'];
c[1] = ['2','2'];
c[2] = ['3','3'];
d[0] = [document.getElementById('g').value,document.getElementById('h').value];
document.getElementById('i').value = c.join(',');
document.getElementById('j').value = d.join(',');
document.getElementById('b').value = c.contains(d);
}
When I call this function with the 'g' and 'h' fields containing 1 and 2 respectively, it still finds it because the resulting string from the join is: 1,1,2,2,3,3
当我用分别包含1和2的“g”和“h”字段调用这个函数时,它仍然会找到它,因为连接的结果字符串是:1、1、2、2、3、3
Since it is doubtful in my situation that I will come across this type of situation, I'm using this. I thought I would share incase someone else couldn't make the chosen answer work either.
因为在我的情况下,我不太可能遇到这种情况,所以我用这个。我想我也会分享,以防别人也不能让我选择的答案发挥作用。
#15
4
Using array .map function that executes a function for every value in an array seems cleanest to me.
使用数组.map函数为数组中的每个值执行一个函数对我来说似乎是最干净的。
裁判:Array.prototype.map()
This method can work well both for simple arrays and for arrays of objects where you need to see if a key/value exists in an array of objects.
对于简单数组和需要查看键/值是否存在于对象数组中的对象数组,此方法都可以很好地工作。
function inArray(myArray,myValue){
var inArray = false;
myArray.map(function(key){
if (key === myValue){
inArray=true;
}
});
return inArray;
};
var anArray = [2,4,6,8]
console.log(inArray(anArray, 8)); // returns true
console.log(inArray(anArray, 1)); // returns false
function inArrayOfObjects(myArray,myValue,objElement){
var inArray = false;
myArray.map(function(arrayObj){
if (arrayObj[objElement] === myValue) {
inArray=true;
}
});
return inArray;
};
var objArray = [{id:4,value:'foo'},{id:5,value:'bar'}]
console.log(inArrayOfObjects(objArray, 4, 'id')); // returns true
console.log(inArrayOfObjects(objArray, 'bar', 'value')); // returns true
console.log(inArrayOfObjects(objArray, 1, 'id')); // returns false
#16
2
function setFound(){
var l = arr.length, textBox1 = document.getElementById("text1");
for(var i=0; i<l;i++)
{
if(arr[i]==searchele){
textBox1 .value = "Found";
return;
}
}
textBox1 .value = "Not Found";
return;
}
This program checks whether the given element is found or not. Id text1 represents id of textbox and searchele represents element to be searched (got fron user); if you want index, use i value
这个程序检查是否找到给定的元素。Id text1表示文本框的Id, searchele表示要搜索的元素(获取fron用户);如果你想要索引,使用i值
#17
1
The simplest solution for a contains
function, would be a function that looks like this :
一个包含函数的最简单的解决方案是,一个像这样的函数:
var contains = function (haystack, needle) {
return !!~haystack.indexOf(needle);
}
Ideally, you wouldn't make this a stand-alone function, though, but part of a helper library :
不过,理想情况下,您不会让它成为一个独立的函数,而是帮助库的一部分:
var helper = {};
helper.array = {
contains : function (haystack, needle) {
return !!~haystack.indexOf(needle);
},
...
};
Now, if you happen to be one of those unlucky people who still needs to support IE<9 and thus can't rely on indexOf
, you could use this polyfill, which I got from the MDN :
现在,如果你碰巧是那些不幸的人,仍然需要支持IE<9,因此不能依赖indexOf,你可以使用这个polyfill,这是我从MDN得到的:
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
var len = o.length >>> 0;
if (len === 0) {
return -1;
}
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
if (n >= len) {
return -1;
}
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
while (k < len) {
if (k in o && o[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
#18
-4
I prefer simplicity:
我更喜欢简单性:
var days = [1, 2, 3, 4, 5];
if ( 2 in days ) {console.log('weekday');}
#1
940
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验证/使用
#2
916
jQuery has a utility function for this:
jQuery为此提供了一个实用函数:
$.inArray(value, array)
Returns index of value
in array
. Returns -1
if array
does not contain value
.
返回数组中值的索引。如果数组不包含值,返回-1。
See also How do I check if an array includes an object in JavaScript?
请参见如何检查数组是否包含JavaScript中的对象?
#3
720
This is generally what the indexOf() method is for. You would say:
这通常是indexOf()方法的用途。你会说:
return arrValues.indexOf('Sam') > -1
#4
228
Array.prototype.includes()
In ES2016, there is Array.prototype.includes()
.
在ES2016中,有array .prototype.include()。
The
includes()
method determines whether an array includes a certain element, returningtrue
orfalse
as appropriate.方法确定数组是否包含某个元素,并根据需要返回true或false。
Example
["Sam", "Great", "Sample", "High"].includes("Sam"); // true
Support
According to kangax and MDN, the following platforms are supported:
根据kangax和MDN,支持以下平台:
- Chrome 47
- Chrome 47
- Edge 14
- 边缘14
- Firefox 43
- Firefox 43
- Opera 34
- 歌剧34
- Safari 9
- Safari 9
- Node 6
- 节点6
Support can be expanded using Babel (using babel-polyfill
) or core-js
. MDN also provides a polyfill:
可以使用Babel(使用Babel -polyfill)或core-js扩展支持。MDN还提供一种polyfill:
if (![].includes) {
Array.prototype.includes = function(searchElement /*, fromIndex*/ ) {
'use strict';
var O = Object(this);
var len = parseInt(O.length) || 0;
if (len === 0) {
return false;
}
var n = parseInt(arguments[1]) || 0;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {k = 0;}
}
var currentElement;
while (k < len) {
currentElement = O[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)) {
return true;
}
k++;
}
return false;
};
}
#5
115
It's almost always safer to use a library like lodash simply because of all the issues with cross-browser compatibilities and efficiency.
使用lodash这样的库几乎总是更安全,因为存在跨浏览器兼容性和效率问题。
Efficiency because you can be guaranteed that at any given time, a hugely popular library like underscore will have the most efficient method of accomplishing a utility function like this.
效率,因为您可以保证,在任何给定的时间,一个非常流行的库(如下划线)将具有完成这样一个实用函数的最有效方法。
_.includes([1, 2, 3], 3); // returns true
If you're concerned about the bulk that's being added to your application by including the whole library, know that you can include functionality separately:
如果您担心通过包含整个库添加到应用程序中的大量内容,那么要知道您可以分别包含以下功能:
var includes = require('lodash/collections/includes');
NOTICE: With older versions of lodash, this was _.contains()
rather than _.includes()
.
注意:对于旧版本的lodash,这是_.contains()而不是_.include()。
#6
46
tl;dr
博士tl;
function includes(k) {
for(var i=0; i < this.length; i++){
if( this[i] === k || ( this[i] !== this[i] && k !== k ) ){
return true;
}
}
return false;
}
Example
例子
function includes(k) {
for(var i=0; i < this.length; i++){
if( this[i] === k || ( this[i] !== this[i] && k !== k ) ){
return true;
}
}
return false;
}
function log(msg){
$('#out').append('<div>' + msg + '</div>');
}
var arr = [1, "2", NaN, true];
arr.includes = includes;
log('var arr = [1, "2", NaN, true];');
log('<br/>');
log('arr.includes(1): ' + arr.includes(1));
log('arr.includes(2): ' + arr.includes(2));
log('arr.includes("2"): ' + arr.includes("2"));
log('arr.includes(NaN): ' + arr.includes(NaN));
log('arr.includes(true): ' + arr.includes(true));
log('arr.includes(false): ' + arr.includes(false));
#out{
font-family:monospace;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=out></div>
Longer Answer
再回答
I know this question isn't really about whether or not to extend built-in objects, but the attempt of the OP and the comments on this answer highlight that debate. My comment from Feb 12, '13 cites an article that outlines this debate really well, however that link broke and I can't edit the original comment because too much time has passed, so I include it here.
我知道这个问题并不是关于是否扩展内置对象,而是OP的尝试和对这个答案的评论突出了这个争论。13年2月12日我的评论引用了一篇文章,很好地概括了这场辩论,但是链接坏了,我不能编辑原来的评论,因为时间太长了,所以我把它写在这里。
If you're looking to extend the built-in Array
object with a contains
method, probably the best and most responsible way to do this would be to use this polyfill from MDN. (See also this section of the MDN article on Prototypical inheritance, which explains that "The only good reason for extending a built-in prototype is to backport the features of newer JavaScript engines; for example Array.forEach, etc.")
如果您希望使用contains方法扩展内置数组对象,那么最好和最负责任的方法可能是使用MDN中的这个polyfill。(还请参阅MDN关于原型继承的文章的这一节,其中解释了“扩展内置原型的唯一好理由是支持更新的JavaScript引擎的特性;例如数组。forEach等。”)
if (!Array.prototype.includes) {
Array.prototype.includes = function(searchElement /*, fromIndex*/ ) {
'use strict';
var O = Object(this);
var len = parseInt(O.length) || 0;
if (len === 0) {
return false;
}
var n = parseInt(arguments[1]) || 0;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {k = 0;}
}
var currentElement;
while (k < len) {
currentElement = O[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)) {
return true;
}
k++;
}
return false;
};
}
Don't want strict equality, or want to choose?
不想要严格的平等,还是想要选择?
function includes(k, strict) {
strict = strict !== false; // default is true
// strict = !!strict; // default is false
for(var i=0; i < this.length; i++){
if( (this[i] === k && strict) ||
(this[i] == k && !strict) ||
(this[i] !== this[i] && k !== k)
) {
return true;
}
}
return false;
}
#7
30
Since ECMAScript6, one can use Set
:
由于ECMAScript6,可以使用Set:
var myArray = ['A', 'B', 'C'];
var mySet = new Set(myArray);
var hasB = mySet.has('B'); // true
var hasZ = mySet.has('Z'); // false
#8
17
My little contribution:
我的小贡献:
function isInArray(array, search)
{
return array.indexOf(search) >= 0;
}
//usage
if(isInArray(my_array, "my_value"))
{
//...
}
#9
16
Given the implementation of indexOf for IE (as described by eyelidlessness):
给定IE的indexOf的实现(用无眼睑描述):
Array.prototype.contains = function(obj) {
return this.indexOf(obj) > -1;
};
#10
15
If you have access to ECMA 5 you can use the some method.
如果您可以访问ECMA 5,您可以使用some方法。
MDN一些方法链接
arrValues = ["Sam","Great", "Sample", "High"];
function namePresent(name){
return name === this.toString();
}
// Note:
// namePresent requires .toString() method to coerce primitive value
// i.e. String {0: "S", 1: "a", 2: "m", length: 3, [[PrimitiveValue]]: "Sam"}
// into
// "Sam"
arrValues.some(namePresent, 'Sam');
=> true;
If you have access to ECMA 6 you can use the includes method.
如果您能够访问ECMA 6,您可以使用include方法。
MDN包括方法链接
arrValues = ["Sam","Great", "Sample", "High"];
arrValues.includes('Sam');
=> true;
#11
11
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.
您可以使用_。索引方法或如果您不想包含整个下划线。在你的app中,你可以看看他们是怎么做的,并提取出必要的代码。
_.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;
};
#12
9
Another option would be to use Array.some
(if available) in the following way:
另一种选择是使用数组。一些(如有)以下列方式:
Array.prototype.contains = function(obj) {
return this.some( function(e){ return e === obj } );
}
The anonymous function passed to Array.some
will return true
if and only if there is an element in the array that is identical to obj
. Absent such an element, the function will not return true
for any of the elements of the array, so Array.some
will return false
as well.
传递给数组的匿名函数。当且仅当数组中有与obj相同的元素时,有些将返回true。如果没有这样的元素,函数将不会返回对数组元素的任何元素。有些也会返回false。
#13
6
Wow, there are a lot of great answers to this question.
哇,这个问题有很多很好的答案。
I didn't see one that takes a reduce
approach so I'll add it in:
我没见过有什么方法可以用reduce方法,所以我把它加进来:
var searchForValue = 'pig';
var valueIsInArray = ['horse', 'cat', 'dog'].reduce(function(previous, current){
return previous || searchForValue === current ? true : false;
}, false);
console.log('The value "' + searchForValue + '" is in the array: ' + valueIsInArray);
Here's a fiddle of it in action.
这里有一个小提琴在演奏。
#14
4
The answer provided didn't work for me, but it gave me an idea:
答案并不适合我,但它给了我一个想法:
Array.prototype.contains = function(obj)
{
return (this.join(',')).indexOf(obj) > -1;
}
It isn't perfect because items that are the same beyond the groupings could end up matching. Such as my example
它并不完美,因为超出分组的相同项最终可能会匹配。比如我的例子
var c=[];
var d=[];
function a()
{
var e = '1';
var f = '2';
c[0] = ['1','1'];
c[1] = ['2','2'];
c[2] = ['3','3'];
d[0] = [document.getElementById('g').value,document.getElementById('h').value];
document.getElementById('i').value = c.join(',');
document.getElementById('j').value = d.join(',');
document.getElementById('b').value = c.contains(d);
}
When I call this function with the 'g' and 'h' fields containing 1 and 2 respectively, it still finds it because the resulting string from the join is: 1,1,2,2,3,3
当我用分别包含1和2的“g”和“h”字段调用这个函数时,它仍然会找到它,因为连接的结果字符串是:1、1、2、2、3、3
Since it is doubtful in my situation that I will come across this type of situation, I'm using this. I thought I would share incase someone else couldn't make the chosen answer work either.
因为在我的情况下,我不太可能遇到这种情况,所以我用这个。我想我也会分享,以防别人也不能让我选择的答案发挥作用。
#15
4
Using array .map function that executes a function for every value in an array seems cleanest to me.
使用数组.map函数为数组中的每个值执行一个函数对我来说似乎是最干净的。
裁判:Array.prototype.map()
This method can work well both for simple arrays and for arrays of objects where you need to see if a key/value exists in an array of objects.
对于简单数组和需要查看键/值是否存在于对象数组中的对象数组,此方法都可以很好地工作。
function inArray(myArray,myValue){
var inArray = false;
myArray.map(function(key){
if (key === myValue){
inArray=true;
}
});
return inArray;
};
var anArray = [2,4,6,8]
console.log(inArray(anArray, 8)); // returns true
console.log(inArray(anArray, 1)); // returns false
function inArrayOfObjects(myArray,myValue,objElement){
var inArray = false;
myArray.map(function(arrayObj){
if (arrayObj[objElement] === myValue) {
inArray=true;
}
});
return inArray;
};
var objArray = [{id:4,value:'foo'},{id:5,value:'bar'}]
console.log(inArrayOfObjects(objArray, 4, 'id')); // returns true
console.log(inArrayOfObjects(objArray, 'bar', 'value')); // returns true
console.log(inArrayOfObjects(objArray, 1, 'id')); // returns false
#16
2
function setFound(){
var l = arr.length, textBox1 = document.getElementById("text1");
for(var i=0; i<l;i++)
{
if(arr[i]==searchele){
textBox1 .value = "Found";
return;
}
}
textBox1 .value = "Not Found";
return;
}
This program checks whether the given element is found or not. Id text1 represents id of textbox and searchele represents element to be searched (got fron user); if you want index, use i value
这个程序检查是否找到给定的元素。Id text1表示文本框的Id, searchele表示要搜索的元素(获取fron用户);如果你想要索引,使用i值
#17
1
The simplest solution for a contains
function, would be a function that looks like this :
一个包含函数的最简单的解决方案是,一个像这样的函数:
var contains = function (haystack, needle) {
return !!~haystack.indexOf(needle);
}
Ideally, you wouldn't make this a stand-alone function, though, but part of a helper library :
不过,理想情况下,您不会让它成为一个独立的函数,而是帮助库的一部分:
var helper = {};
helper.array = {
contains : function (haystack, needle) {
return !!~haystack.indexOf(needle);
},
...
};
Now, if you happen to be one of those unlucky people who still needs to support IE<9 and thus can't rely on indexOf
, you could use this polyfill, which I got from the MDN :
现在,如果你碰巧是那些不幸的人,仍然需要支持IE<9,因此不能依赖indexOf,你可以使用这个polyfill,这是我从MDN得到的:
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
var len = o.length >>> 0;
if (len === 0) {
return -1;
}
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
if (n >= len) {
return -1;
}
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
while (k < len) {
if (k in o && o[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
#18
-4
I prefer simplicity:
我更喜欢简单性:
var days = [1, 2, 3, 4, 5];
if ( 2 in days ) {console.log('weekday');}