var object = {
b: { c: 4 }, d: [{ e: 5 }, { e: 6 }]
};
console.log( parse(object, 'b.c') == 4 ) //true
console.log( parse(object, 'd[0].e') == 5 ) //true
console.log( parse(object, 'd.0.e') == 5 ) //true
console.log( parse(object, 'd[1].e') == 6 ) //true
console.log( parse(object, 'd.1.e') == 6 ) //true
console.log( parse(object, 'f') == 'undefined' ) //true
编程:
法一:
//使用正则表达式
function parse(obj, str){
return new Function('obj', 'return obj.' + str.replace(/\.(\d+)/g, '\[$1\]'))(obj);
}
法二
function parse(obj,str) {
str = str.replace(/\[(\d+)\]/g,'.$1');
arr = str.split('.');
arr.forEach(function(item) {
obj = obj[item];
})
return obj;
}