【发布时间】:2011-04-07 04:29:47
【问题描述】:
如何在不使用 JavaScript 中的 for 循环的情况下搜索数组中对象的属性?
如果数组是一个简单的数组,我可以使用array.indexOf(value) 来获取索引,但是如果数组是对象数组呢?除了循环还有其他方式吗?
例如,ar = [{x,y},{p,q},{u,v}]。如果搜索v,它应该返回数组索引为2。
【问题讨论】:
标签: javascript arrays
如何在不使用 JavaScript 中的 for 循环的情况下搜索数组中对象的属性?
如果数组是一个简单的数组,我可以使用array.indexOf(value) 来获取索引,但是如果数组是对象数组呢?除了循环还有其他方式吗?
例如,ar = [{x,y},{p,q},{u,v}]。如果搜索v,它应该返回数组索引为2。
【问题讨论】:
标签: javascript arrays
在数组中搜索值通常需要sequential search,这需要您遍历每个项目,直到找到匹配项。
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;
【讨论】:
filter() 方法,但这对于您的要求来说仍然过于复杂。
Searching for objects in JavaScript arrays
javascript:
/* quick fix naive short solution to be posted soon */
/* array of objects with primitive property values only and no wrinkles */
.
javascript:
alert(
JSON.stringify(
[{x:1,y:2},,,{p:"q"},{u:{},vx:[],x:{y:{},x:5}}]
) . match(/"x":/g)
)
和
javascript: /* Does the need to fortify this code imply JSON is stronger? */
alert( /* See wrinkles below */
[{x:1,y:2},,,{p:"q"},{u:{},vx:[],x:{y:{},x:5}}] . toSource() .
/*
match(/({|,)\s*x:/g) . join() . replace(/({|,)\s*x:/g,"x:")
finds `x:,x:,x:`
*/
replace(/(({|,)\s*)([^,{:]*):/g,'$1"$3":') . match(/"x":/g)
)
找到"x":,"x":,"x":。
找到特定的财产,完成交易?
提示,提示(但对于嵌套的动物,必须适当减弱和截肢):
javascript:
alert(
JSON.stringify([{x:1,y:2},{p:"q"},{u:{},v:[],x:{y:{},x:5}}]) .
match(/"[^"]*":/g)
)
找到"x":,"y":,"p":,"u":,"v":,"x":,"y":,"x":(所有属性 - 现在完成了吗?)
更多(更多)大脑劳损疼痛将找到x:values 和数组位置索引(提示计数顶级,'s)。
截断和衰减提示(仅删除嵌套数组和对象,,见皱纹):
javascript:debug=false;
animal=[
{x:1,y:2},,,{p:"q"},
[ {u:{},vx:[,,], x:{y:{xx:''},x:5} }, "hmmm comma x colon \" monster" ],
];
animal=animal.toSource().replace(/\[(.*)]/,"$1");
/* */ if(debug){
alert(animal);
animal=animal.replace(/\[([^[\]]*)\]/g,
function(a,b,c,d){alert([a,b,c,d].join("\n\n"));return a});
while(animal.search(/\{.*\}|\[.*\]/)>-1){
animal=animal.replace(/\{([^{}]*)\}|\[(.*)\]/g,
function(a,b,c,d){alert([a,"\n",b,"\n",c]);return b.replace(/,/g,";")});
alert(animal); }
/* */ }
/* the while loops on nesting depth not top array length */
while(animal.search(/\{.*\}|\[.*\]/)>-1)
animal=animal.replace(/\{([^{}]*)\}|\[(.*)\]/g, /* implicit g loop */
function(a,b,c,d){return (b+c).replace(/,/g," ")}); /* ditto */
alert(animal); /* as opposed to a non-lert animal? */
皱纹:
.toSource() 比JSON 更强大(但...见上文)并处理更多情况@, 的。 . .如 . . . [",,or",,{p:"1,2,3,"}] {x:...} 或 {"x":...} 。 . .如 . . . ['{"x":...}'," and ","{x:...}",,]JSON 或toSource 搞砸上述编码)【讨论】: