你可以創建自己的訪問器功能:
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;
}
將其封裝在'嘗試{...}趕上(E){...}' – phylax
看來這個問題是重複的。我的答案與另一個線程中的[@ kennebec's](http://stackoverflow.com/a/2631521/1529630)幾乎相同;我沒有模仿他,強硬。 – Oriol