如何确定Javascript数组是否包含具有等于给定值的属性的对象? [英] How to determine if Javascript array contains an object with an attribute that equals a given value?
问题描述
我有一个类似的数组
vendors = [{
Name: 'Magenic',
ID: 'ABC'
},
{
Name: 'Microsoft',
ID: 'DEF'
} // and so on...
];
如何检查此数组以查看Magenic"是否存在存在吗?我不想循环,除非我必须.我正在处理可能有几千条记录.
How do I check this array to see if "Magenic" exists? I don't want to loop, unless I have to. I'm working with potentially a couple thousand records.
推荐答案
2018 edit:这个答案是从 2011 年开始的,在浏览器广泛支持数组过滤方法和箭头函数之前.看看 CAFxX 的回答.
2018 edit: This answer is from 2011, before browsers had widely supported array filtering methods and arrow functions. Have a look at CAFxX's answer.
没有神奇"的方法可以在没有循环的情况下检查数组中的某些内容.即使您使用某个函数,该函数本身也会使用循环.您可以做的是在找到所需内容后立即跳出循环,以最大限度地减少计算时间.
There is no "magic" way to check for something in an array without a loop. Even if you use some function, the function itself will use a loop. What you can do is break out of the loop as soon as you find what you're looking for to minimize computational time.
var found = false;
for(var i = 0; i < vendors.length; i++) {
if (vendors[i].Name == 'Magenic') {
found = true;
break;
}
}
这篇关于如何确定Javascript数组是否包含具有等于给定值的属性的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!