您可以创建自己的访问器功能:
function access(obj, path) {
var arr = path.split('/');
while(obj && arr.length)
obj = obj[arr.shift()];
return obj;
}
并像这样使用它:
var bank = {
customerlist: {customer: [{address: 'foo'}]}
}
access(bank, 'customerlist/customer/0/address'); // 'foo'
access(bank, 'bar/foo/foobar'); // undefined (no error)
还可以考虑使用...
function access(obj, path) {
var arr = path.split('/');
while(obj!=null && arr.length)
obj = obj[arr.shift()];
return obj;
}
...如果您想access
与非对象一起使用,例如您想access('', 'length')
返回0
解释,
function access(obj, path) {
var arr = path.split('/');
while (
obj /* To avoid `null` and `undefined`. Also consider `obj != null` */
&& /* Logical AND */
arr.length /* Check that `arr` still has elements */
) {
obj = obj[arr.shift()]; /* `arr.shift()` extracts the first
element is `arr` */
}
return obj;
}