找出JavaScript数组是否包含值的最简洁有效的方法是什么?
这是我知道的唯一方法:
function contains(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
有没有更好、更简洁的方法来实现这一点?
这与堆栈溢出问题密切相关。在JavaScript数组中查找项目的最佳方法是什么?它解决了使用indexOf查找数组中的对象的问题。
类似的事情:通过“search lambda”查找第一个元素:
Array.prototype.find = function(search_lambda) {
return this[this.map(search_lambda).indexOf(true)];
};
用法:
[1,3,4,5,8,3,5].find(function(item) { return item % 2 == 0 })
=> 4
咖啡脚本也一样:
Array.prototype.find = (search_lambda) -> @[@map(search_lambda).indexOf(true)]
indexOf可能是,但它是“ECMA-262标准的JavaScript扩展;因此,它可能不会出现在标准的其他实现中。”
例子:
[1, 2, 3].indexOf(1) => 0
["foo", "bar", "baz"].indexOf("bar") => 1
[1, 2, 3].indexOf(4) => -1
AFAICS Microsoft没有提供某种替代方案,但如果您愿意,可以在Internet Explorer(以及其他不支持indexOf的浏览器)中的数组中添加类似的功能,正如Google快速搜索所显示的(例如,这一个)。
Object.keys,用于获取对象的所有属性名称,并筛选与指定字符串完全或部分匹配的所有值。
函数filterByValue(数组,字符串){返回array.filter(o=>Object.keys(o).some(k=>o[k].toLowerCase().includes(string.toLoweCase()));}常量数组OfObject=[{name:“Paul”,country:'加拿大',}, {name:'Lea',国家:“意大利”,}, {name:“John”,country:'意大利'}];console.log(filterByValue(arrayOfObject,'lea'));//〔{名称:‘Lea’,国家:‘意大利’}〕console.log(filterByValue(arrayOfObject,'ita'));//[{名称:“Lea”,国家:“Italy”},{名称“John”,国家“Italy'”}]
您还可以按特定关键字进行筛选,例如。
Object.keys(o).some(k => o.country.toLowerCase().includes(string.toLowerCase())));
现在,您可以在过滤后检查数组计数,以检查值是否包含。
希望这有帮助。
这可能是一个详细而简单的解决方案。
//plain array
var arr = ['a', 'b', 'c'];
var check = arr.includes('a');
console.log(check); //returns true
if (check)
{
// value exists in array
//write some codes
}
// array with objects
var arr = [
{x:'a', y:'b'},
{x:'p', y:'q'}
];
// if you want to check if x:'p' exists in arr
var check = arr.filter(function (elm){
if (elm.x == 'p')
{
return elm; // returns length = 1 (object exists in array)
}
});
// or y:'q' exists in arr
var check = arr.filter(function (elm){
if (elm.y == 'q')
{
return elm; // returns length = 1 (object exists in array)
}
});
// if you want to check, if the entire object {x:'p', y:'q'} exists in arr
var check = arr.filter(function (elm){
if (elm.x == 'p' && elm.y == 'q')
{
return elm; // returns length = 1 (object exists in array)
}
});
// in all cases
console.log(check.length); // returns 1
if (check.length > 0)
{
// returns true
// object exists in array
//write some codes
}
我们使用以下代码段(用于对象、数组和字符串):
/*
* @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