全部评论
尝试了一下: function getValueByPath(a, str) {
const keys = str.split('.');
try {
const result = keys.reduce((acc, current) => {
if (/.+\[\d+\]/g.test(current)) {
const matchs = (/^(.+)\[(\d+)\]/g).exec(current);
const arr = acc[matchs[1]];
const index = matchs[2];
return arr[index];
}
const key = current;
return acc[key];
}, a);
return result;
} catch (error) {
return undefined
}
}
const x = { a: { b: [{ c: 1 }] } };
const y = [];
console.log(getValueByPath(x, 'a.b[0].c'));
console.log(getValueByPath(y, 'a.b[0].c'));
顺便问下,你什么时候投的以及什么时候笔试的,为什么我还没收到面试通知。
送花
回复
分享
第二个参数用按符号.分割 str.split()会变成一个数组 for loop这个数组 每个元素作为当前对象的属性 如x[a] 存在值继续往第下 不存在就return undefined 退出
送花
回复
分享
滴滴
官网直投
麻烦问一下几号笔试的
送花
回复
分享
......
送花
回复
分享
相关推荐
点赞 评论 收藏
转发