我有一个数组
vendors = [{
Name: 'Magenic',
ID: 'ABC'
},
{
Name: 'Microsoft',
ID: 'DEF'
} // and so on...
];
我如何检查这个数组,看看“Magenic”是否存在?我不想循环,除非迫不得已。我可能要处理几千条记录。
我有一个数组
vendors = [{
Name: 'Magenic',
ID: 'ABC'
},
{
Name: 'Microsoft',
ID: 'DEF'
} // and so on...
];
我如何检查这个数组,看看“Magenic”是否存在?我不想循环,除非迫不得已。我可能要处理几千条记录。
当前回答
目前最简单的方法:
if (vendors.findIndex(item => item.Name == "Magenic") == -1) {
//not found item
} else {
//found item
}
其他回答
除非你想这样重组:
vendors = {
Magenic: {
Name: 'Magenic',
ID: 'ABC'
},
Microsoft: {
Name: 'Microsoft',
ID: 'DEF'
} and so on...
};
你可以这样做如果(vendor . magnetic)
你必须循环
Var without2 = (arr, args) => arr。过滤(v => v.id !== args.id); 例子:
without2 ([{id: 1}, {id: 1}, {id: 2}), {id: 2})
结果: without2 ([{id: 1}, {id: 1}, {id: 2}), {id: 2})
2018编辑:这个答案来自2011年,当时浏览器还没有广泛支持数组过滤方法和箭头函数。来看看CAFxX的答案吧。
没有“神奇”的方法可以在没有循环的情况下检查数组中的内容。即使你使用某个函数,这个函数本身也会使用循环。您可以做的是,一旦找到要查找的内容,就立即跳出循环,以最小化计算时间。
var found = false;
for(var i = 0; i < vendors.length; i++) {
if (vendors[i].Name == 'Magenic') {
found = true;
break;
}
}
或者你可以这样做:
const find = (key, needle) => return !!~vendors.findIndex(v => (v[key] === needle));
不需要重新发明轮子循环,至少不显式地(使用箭头函数,仅限现代浏览器):
if (vendors.filter(e => e.Name === 'Magenic').length > 0) {
/* vendors contains the element we're looking for */
}
或者,更好的是,使用some,因为它允许浏览器在找到匹配的元素时立即停止,所以它会更快:
if (vendors.some(e => e.Name === 'Magenic')) {
/* vendors contains the element we're looking for */
}
或等价的(在这种情况下)找到:
if (vendors.find(e => e.Name === 'Magenic')) {
/* same result as above, but a different function return type */
}
你甚至可以通过使用findIndex来获取该元素的位置:
const i = vendors.findIndex(e => e.Name === 'Magenic');
if (i > -1) {
/* vendors contains the element we're looking for, at index "i" */
}
如果你需要兼容糟糕的浏览器,那么你最好的选择是:
if (vendors.filter(function(e) { return e.Name === 'Magenic'; }).length > 0) {
/* vendors contains the element we're looking for */
}