找出JavaScript数组是否包含值的最简洁有效的方法是什么?
这是我知道的唯一方法:
function contains(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
有没有更好、更简洁的方法来实现这一点?
这与堆栈溢出问题密切相关。在JavaScript数组中查找项目的最佳方法是什么?它解决了使用indexOf查找数组中的对象的问题。
使用lodash的一些功能。
它简洁、准确,并且具有强大的跨平台支持。
接受的答案甚至不符合要求。
要求:推荐最简洁有效的方法来确定JavaScript数组是否包含对象。
接受答案:
$.inArray({'b': 2}, [{'a': 1}, {'b': 2}])
> -1
我的建议:
_.some([{'a': 1}, {'b': 2}], {'b': 2})
> true
笔记:
$.inArray可以很好地确定标量数组中是否存在标量值。。。
$.inArray(2, [1,2])
> 1
…但这个问题显然需要一种有效的方法来确定数组中是否包含对象。
为了处理标量和对象,可以执行以下操作:
(_.isObject(item)) ? _.some(ary, item) : (_.indexOf(ary, item) > -1)
我们使用以下代码段(用于对象、数组和字符串):
/*
* @function
* @name Object.prototype.inArray
* @description Extend Object prototype within inArray function
*
* @param {mix} needle - Search-able needle
* @param {bool} searchInKey - Search needle in keys?
*
*/
Object.defineProperty(Object.prototype, 'inArray',{
value: function(needle, searchInKey){
var object = this;
if( Object.prototype.toString.call(needle) === '[object Object]' ||
Object.prototype.toString.call(needle) === '[object Array]'){
needle = JSON.stringify(needle);
}
return Object.keys(object).some(function(key){
var value = object[key];
if( Object.prototype.toString.call(value) === '[object Object]' ||
Object.prototype.toString.call(value) === '[object Array]'){
value = JSON.stringify(value);
}
if(searchInKey){
if(value === needle || key === needle){
return true;
}
}else{
if(value === needle){
return true;
}
}
});
},
writable: true,
configurable: true,
enumerable: false
});
用法:
var a = {one: "first", two: "second", foo: {three: "third"}};
a.inArray("first"); //true
a.inArray("foo"); //false
a.inArray("foo", true); //true - search by keys
a.inArray({three: "third"}); //true
var b = ["one", "two", "three", "four", {foo: 'val'}];
b.inArray("one"); //true
b.inArray('foo'); //false
b.inArray({foo: 'val'}) //true
b.inArray("{foo: 'val'}") //false
var c = "String";
c.inArray("S"); //true
c.inArray("s"); //false
c.inArray("2", true); //true
c.inArray("20", true); //false