搜索在JavaScript数组对象 [英] Searching for objects in JavaScript arrays
本文介绍了搜索在JavaScript数组对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何寻找数组中对象的属性,而无需使用中的JavaScript
循环?
How do I search for the property of an object in an array without using for
loops in JavaScript?
如果数组是一个简单的,我可以使用 array.indexOf(值)
来的景气指数,但是如果数组对象数组是什么?除了循环任何其他方式?
If the array is a simple one I can use array.indexOf(value)
to get the index, but what if the array is an array of objects? Other than looping any other way?
例如, AR = [{X,Y},{P,Q},{U,V}]
。如果搜索 v
,它应该返回数组索引为2。
For example, ar = [{x,y},{p,q},{u,v}]
. If searched for v
, it should return the array index as 2.
推荐答案
搜索数组中的值通常需要的顺序搜索,这就需要你遍历每个项目,直到你找到一个匹配。
Searching for a value in an array typically requires a sequential search, which requires you to loop over each item until you find a match.
function search(ar, value) {
var i, j;
for (i = 0; i < ar.length; i++) {
for (j in ar[i]) {
if (ar[i][j] === value) return i;
}
}
}
search([{'x': 'y'}, {'p': 'q'}, {'u': 'v'}], 'v'); // returns 2;
这篇关于搜索在JavaScript数组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文