问题描述比如后台可能返回一个对象let obj = {
school: {
class1: {
student: 50
}
}}我需要取出里面student的值,但是有可能后台返回给我的是 {school: null} 或者 {} 甚至是 undefined因此我取值时可能是let student = obj?(obj.school?(obj.school.class1?(obj.school.class1.studnet?obj.school.class1.studnet:''):''):''):'';这显然可读性不好,也麻烦,请问有什么方式可以优雅的处理这种取值并且防止Cannot read property 'xxx' of undefined 的报错吗
1 回答
慕的地10843
TA贡献1785条经验 获得超8个赞
如果不用考虑兼容性的话,加个Proxy监听get是个很合适的办法
/**
* @param target
* @param exec 取值属性
* @returns {*}
*/function getter(target, exec = '_') { return new Proxy({}, { get: (o, n) => { return n === exec ?
target :
getter(typeof target === 'undefined' ? target : target[n], exec)
}
});
}let obj = {
school: {
class1: {
student: 50
}
}
};console.log(getter(obj).school.class1.student._)//50console.log(getter(obj).school1.class11.student._)//undefined添加回答
举报
0/150
提交
取消
