查找对象是否在数组中的最佳方法是什么?
这是我知道的最好的方法:
function include(arr, obj) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] == obj) return true;
}
}
console.log(include([1, 2, 3, 4], 3)); // true
console.log(include([1, 2, 3, 4], 6)); // undefined
查找对象是否在数组中的最佳方法是什么?
这是我知道的最好的方法:
function include(arr, obj) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] == obj) return true;
}
}
console.log(include([1, 2, 3, 4], 3)); // true
console.log(include([1, 2, 3, 4], 6)); // undefined
从 ECMAScript 2016 开始,您可以使用includes()
arr.includes(obj);
如果要支持 IE 或其他旧版浏览器:
function include(arr,obj) {
return (arr.indexOf(obj) != -1);
}
编辑:但这不适用于 IE6、7 或 8。如果它不存在,最好的解决方法是自己定义它:
Mozilla 的(ECMA-262) 版本:
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(searchElement /*, fromIndex */)
{
"use strict";
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (len === 0)
return -1;
var n = 0;
if (arguments.length > 0)
{
n = Number(arguments[1]);
if (n !== n)
n = 0;
else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
if (n >= len)
return -1;
var k = n >= 0
? n
: Math.max(len - Math.abs(n), 0);
for (; k < len; k++)
{
if (k in t && t[k] === searchElement)
return k;
}
return -1;
};
}
丹尼尔詹姆斯的版本:
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (obj, fromIndex) {
if (fromIndex == null) {
fromIndex = 0;
} else if (fromIndex < 0) {
fromIndex = Math.max(0, this.length + fromIndex);
}
for (var i = fromIndex, j = this.length; i < j; i++) {
if (this[i] === obj)
return i;
}
return -1;
};
}
公鸡酸的版本:
Array.prototype.hasObject = (
!Array.indexOf ? function (o)
{
var l = this.length + 1;
while (l -= 1)
{
if (this[l - 1] === o)
{
return true;
}
}
return false;
} : function (o)
{
return (this.indexOf(o) !== -1);
}
);
如果您使用的是 jQuery:
$.inArray(5 + 5, [ "8", "9", "10", 10 + "" ]);
首先,indexOf
在没有 JavaScript 的浏览器中实现它。例如,请参阅Erik Arvidsson 的数组 extras(还有相关的博客文章)。然后您可以使用indexOf
而不必担心浏览器支持。这是他的实现的稍微优化的版本indexOf
:
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (obj, fromIndex) {
if (fromIndex == null) {
fromIndex = 0;
} else if (fromIndex < 0) {
fromIndex = Math.max(0, this.length + fromIndex);
}
for (var i = fromIndex, j = this.length; i < j; i++) {
if (this[i] === obj)
return i;
}
return -1;
};
}
它已更改为存储长度,因此不需要每次迭代都查找它。但差别不是很大。不太通用的功能可能会更快:
var include = Array.prototype.indexOf ?
function(arr, obj) { return arr.indexOf(obj) !== -1; } :
function(arr, obj) {
for(var i = -1, j = arr.length; ++i < j;)
if(arr[i] === obj) return true;
return false;
};
我更喜欢使用标准功能,并在真正需要时保留这种微优化。但是,如果您热衷于微优化,我将评论中与 roosterononacid 相关的基准调整为数组中的基准搜索。虽然它们非常粗糙,但完整的调查将测试具有不同类型、不同长度的数组并找到出现在不同位置的对象。
如果数组未排序,则实际上没有更好的方法(除了使用上面提到的 indexOf,我认为这相当于同一件事)。如果数组已排序,则可以进行二进制搜索,其工作原理如下:
二分查找的运行时间与数组长度的对数成正比,因此它比查看每个单独的元素要快得多。
[].has(obj)
假设.indexOf()
已实现
Object.defineProperty( Array.prototype,'has',
{
value:function(o, flag){
if (flag === undefined) {
return this.indexOf(o) !== -1;
} else { // only for raw js object
for(var v in this) {
if( JSON.stringify(this[v]) === JSON.stringify(o)) return true;
}
return false;
},
// writable:false,
// enumerable:false
})
!!!不要这样做,Array.prototype.has=function(){...
因为您将在每个数组中添加一个可枚举元素,并且 js 已损坏。
//use like
[22 ,'a', {prop:'x'}].has(12) // false
["a","b"].has("a") // true
[1,{a:1}].has({a:1},1) // true
[1,{a:1}].has({a:1}) // false
使用第二个参数(标志)强制按值而不是参考进行比较
比较原始对象
[o1].has(o2,true) // true if every level value is same
这取决于你的目的。如果您为 Web 编程,请避免indexOf
,Internet Explorer 6 不支持它(其中很多仍在使用!),或者有条件地使用:
if (yourArray.indexOf !== undefined) result = yourArray.indexOf(target);
else result = customSlowerSearch(yourArray, target);
indexOf
可能是用本机代码编码的,所以它比你在 JavaScript 中可以做的任何事情都要快(如果数组合适,二进制搜索/二分法除外)。注意:这是一个品味问题,但我会return false;
在你的例程结束时做一个,返回一个真正的布尔值......
这是给你的一些元知识 - 如果你想知道你可以用数组做什么,请查看文档 - 这是 Mozilla 的数组页面
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array
在那里你会看到对 indexOf 的引用,它是在 Javascript 1.6 中添加的
此处详细介绍了一种检查对象是否为 javascript 中的数组的可靠方法:
这是我附加到“容器”的xa.js框架中的两个函数。utils = {}
这些应该可以帮助您正确检测阵列。
var utils = {};
/**
* utils.isArray
*
* Best guess if object is an array.
*/
utils.isArray = function(obj) {
// do an instanceof check first
if (obj instanceof Array) {
return true;
}
// then check for obvious falses
if (typeof obj !== 'object') {
return false;
}
if (utils.type(obj) === 'array') {
return true;
}
return false;
};
/**
* utils.type
*
* Attempt to ascertain actual object type.
*/
utils.type = function(obj) {
if (obj === null || typeof obj === 'undefined') {
return String (obj);
}
return Object.prototype.toString.call(obj)
.replace(/\[object ([a-zA-Z]+)\]/, '$1').toLowerCase();
};
如果您想检查一个对象是否在数组中,我还将包含以下代码:
/**
* Adding hasOwnProperty method if needed.
*/
if (typeof Object.prototype.hasOwnProperty !== 'function') {
Object.prototype.hasOwnProperty = function (prop) {
var type = utils.type(this);
type = type.charAt(0).toUpperCase() + type.substr(1);
return this[prop] !== undefined
&& this[prop] !== window[type].prototype[prop];
};
}
最后是这个 in_array 函数:
function in_array (needle, haystack, strict) {
var key;
if (strict) {
for (key in haystack) {
if (!haystack.hasOwnProperty[key]) continue;
if (haystack[key] === needle) {
return true;
}
}
} else {
for (key in haystack) {
if (!haystack.hasOwnProperty[key]) continue;
if (haystack[key] == needle) {
return true;
}
}
}
return false;
}