这是一个不需要异常处理的变体..会更快吗?我对此表示怀疑。会不会更干净?好吧,这取决于个人喜好.. 当然,这只是一个小的演示原型,我相信已经存在更好的“JSON 查询”库。
// returns the parent object for the given property
// or undefined if there is no such object
function resolveParent (obj, path) {
var parts = path.split(/[.]/g);
var parent;
for (var i = 0; i < parts.length && obj; i++) {
var p = parts[i];
if (p in obj) {
parent = obj;
obj = obj[p];
} else {
return undefined;
}
}
return parent;
}
// omit initial parent/object in path, but include property
// and changing from [] to .
var o = resolveParent(x, "a.b.0.c.d.2.e");
if (o) {
// note duplication of property as above method finds the
// parent, should it exist, so still access the property
// as normal
alert(o.e);
}