我现在使用的函数来检查这是如下:
function inArray(needle,haystack)
{
var count=haystack.length;
for(var i=0;i<count;i++)
{
if(haystack[i]===needle){return true;}
}
return false;
}
它的工作原理。还有更好的办法吗?
我现在使用的函数来检查这是如下:
function inArray(needle,haystack)
{
var count=haystack.length;
for(var i=0;i<count;i++)
{
if(haystack[i]===needle){return true;}
}
return false;
}
它的工作原理。还有更好的办法吗?
当前回答
你可以使用indexOf,但是在上一个版本的ie浏览器中不太好用。 代码:
function isInArray(value, array) {
return array.indexOf(value) > -1;
}
执行:
isInArray(1, [1,2,3]); // true
我建议您使用以下代码:
function inArray(needle, haystack) {
var length = haystack.length;
for (var i = 0; i < length; i++) {
if (haystack[i] == needle)
return true;
}
return false;
}
其他回答
代码:
function isInArray(value, array) {
return array.indexOf(value) > -1;
}
执行:
isInArray(1, [1,2,3]); // true
更新(2017):
在遵循ECMAScript 2016 (ES7)标准的现代浏览器中,您可以使用函数Array.prototype。Includes,这使得检查数组中是否存在项变得更容易:
Const数组= [1,2,3]; Const值= 1; const isInArray = array.includes(value); console.log (isInArray);/ /正确的
只需使用indexOf:
haystack.indexOf(needle) >= 0
如果你想要支持旧的Internet explorer (< IE9),你必须包含你当前的代码作为一种变通方法。
除非您的列表是排序的,否则您需要将每个值与指针进行比较。因此,您的解决方案和indexOf都必须平均执行n/2个比较。然而,由于indexOf是一个内置方法,它可能会使用额外的优化,在实践中会稍微快一些。注意,除非应用程序在列表中搜索非常频繁(比如每秒1000次),或者列表非常庞大(比如100k个条目),否则速度差异并不重要。
你可以使用indexOf,但是在上一个版本的ie浏览器中不太好用。 代码:
function isInArray(value, array) {
return array.indexOf(value) > -1;
}
执行:
isInArray(1, [1,2,3]); // true
我建议您使用以下代码:
function inArray(needle, haystack) {
var length = haystack.length;
for (var i = 0; i < length; i++) {
if (haystack[i] == needle)
return true;
}
return false;
}
在lodash中你可以使用_。Includes(它也是_.contains的别名)
你可以搜索整个数组:
_.includes([1, 2, 3], 1); // true
你可以从一个起始索引搜索数组:
_.includes([1, 2, 3], 1, 1); // false (begins search at index 1)
搜索一个字符串:
_.includes('pebbles', 'eb'); // true (string contains eb)
也适用于检查简单的对象数组:
_.includes({ 'user': 'fred', 'age': 40 }, 'fred'); // true
_.includes({ 'user': 'fred', 'age': false }, false); // true
关于最后一种情况需要注意的一点是,它适用于字符串、数字和布尔值等原语,但不能搜索数组或对象
_.includes({ 'user': 'fred', 'age': {} }, {}); // false
_.includes({ 'user': [1,2,3], 'age': {} }, 3); // false
ECMAScript 2016为数组合并了一个include()方法,专门解决这个问题,所以现在是首选方法。
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, 3].includes(1, 2); // false (second parameter is the index position in this array at which to begin searching)
截至2018年7月,这已经在几乎所有主流浏览器中实现,如果你需要支持旧浏览器,可以使用polyfill。
编辑:注意,如果数组中的项是一个对象,则返回false。这是因为相似的对象在JavaScript中是两个不同的对象。