题目要求
//实现一个函数:
function get(){
//内容...
}
//const obj = { selector: { to: { toutiao: 'FE coder' } }, target: [1, 2, { name: 'byted' }] };
// 运行代码 get(obj, 'selector.to.toutiao', 'target[0]', 'target[2].name')
// 输出结果:// ['FE coder', 1, 'byted']
实现了两种方法
方法1:
const get = (obj, s) => {
const arr = s.split('.');
let item;
while (arr.length) {
const idx = arr.shift();
item = obj[idx];
obj = item;
}
return item;
}
const toDot = (s) => {
let res = s.replace(/\[/g, '.').replace(/\]/g, '');
return res;
}
function getValue(){
const args = [...arguments];
const _obj = args.shift();
let res = [];
for (let i = 0; i < args.length; i++) {
res.push(get(_obj, toDot(args[i])));
}
return res;
}
方法2:
//方法二(使用new Function()+模板字符串):
function getValue2(data, ...args) {
const res = JSON.stringify(data);
return args.map((item) => (new Function(`try {return ${res}.${item} } catch(e) {}`))());
}