如何确定一个对象是否在数组中是最佳方式?
这是我所知道的最佳方法:
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。最好的解决方法是如果IE版本低于9,则自己定义它:
Mozilla's (ECMA-262) version:
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;
};
}
Daniel James's version:
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;
};
}
roosteronacid's version:
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 + "" ]);
if(-1 !=$.inArray(...)) ...
。 - johndodo首先,在JavaScript中实现indexOf
,适用于没有该功能的浏览器。例如,查看Erik Arvidsson的数组扩展(还有相关博客文章)。然后,您可以使用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在评论中提到的基准测试,用于在数组中搜索进行基准测试。虽然它们相当简单,但完整的研究将测试具有不同类型、不同长度和查找出现在不同位置的对象的数组。
[ ].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;
,以返回一个真正的布尔值...
在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;
}