对象
-
let obj = { user: { name: "zhang", age: 20, school: { name: "清华", class: 3, grader: 1 } } }
-
例:获取
obj.user.school.name
- 首先使用
split
,转为数组 - 然后使用
shift()
方法每次取出最前面的属性名, 存放在curr
中 - 新建一个
res
对象,先要判断res[curr]
是否为undefined
, 让res = res[curr]
- 最后返回
res
- 首先使用
-
方法一:
-
function fn(path, obj) { let res = obj, curr, keys = path.split("."); while (curr = keys.shift()) { if(!res[curr]) { return "undefined" } else { res = res[curr] } } return res; } let result = fn("user.school.name", obj) console.log(result);
-
方法二:
-
function fn(path, obj) { return path.split(".").reduce((data, curr) => { return data[curr] }, obj) } let result = fn("user.school.name", obj) console.log(result);