我有一个像
vendors = [{
Name: 'Magenic',
ID: 'ABC'
},
{
Name: 'Microsoft',
ID: 'DEF'
} // and so on...
];
如何检查此数组以查看“Magenic”是否存在?我不想循环,除非我必须这样做。我正在处理可能有几千条记录。
原文由 David Lozzi 发布,翻译遵循 CC BY-SA 4.0 许可协议
我有一个像
vendors = [{
Name: 'Magenic',
ID: 'ABC'
},
{
Name: 'Microsoft',
ID: 'DEF'
} // and so on...
];
如何检查此数组以查看“Magenic”是否存在?我不想循环,除非我必须这样做。我正在处理可能有几千条记录。
原文由 David Lozzi 发布,翻译遵循 CC BY-SA 4.0 许可协议
无需重新发明车轮循环,至少不是明确的(使用 箭头函数, 仅限现代浏览器):
if (vendors.filter(e => e.Name === 'Magenic').length > 0) {
/* vendors contains the element we're looking for */
}
或者, 更好 的是,使用 一些,因为它允许浏览器在找到一个匹配的元素后立即停止,因此它会更快:
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 */
}
原文由 CAFxX 发布,翻译遵循 CC BY-SA 4.0 许可协议
10 回答11.7k 阅读
2 回答3.2k 阅读✓ 已解决
4 回答2.2k 阅读✓ 已解决
3 回答1.2k 阅读✓ 已解决
3 回答837 阅读✓ 已解决
3 回答1k 阅读✓ 已解决
2 回答1.2k 阅读✓ 已解决
2018 年编辑:这个答案来自 2011 年,当时浏览器还没有广泛支持数组过滤方法和箭头函数。看看 CAFxX 的回答。
没有“神奇”的方法可以在没有循环的情况下检查数组中的某些内容。即使您使用某些函数,该函数本身也会使用循环。您可以做的是在您找到所需内容后立即跳出循环,以最大限度地减少计算时间。