头条面试题:实现一个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']
简而言之,这就是一个将字符串转化为变量名的题目
方法一:使用eval()函数
const obj = { selector: { to: { toutiao: "FE Coder"} }, target: [1, 2, { name: 'byted'}]}; // [ 'FE Coder', 1, 'byted'] //get(obj, 'selector.to.toutiao', 'target[0]', 'target[2].name'); function get(obj,x,y,z){ //把字符串变为变量 x=(eval("obj."+x)); y=(eval("obj."+y)); z=(eval("obj."+z)); console.log(x,y,z); } get(obj,'selector.to.toutiao','target[0]','target[2].name')
方法二:使用模板字符串 ``
function get(data, ...args) { const res = JSON.stringify(data); return args.map((item) => (new Function(`try {return ${res}.${item} } catch(e) {}`))()); } const obj = { selector: { to: { toutiao: "FE Coder"} }, target: [1, 2, { name: 'byted'}]}; console.log(get(obj, 'selector.to.toutiao', 'target[0]', 'target[2].name', 'asd'));