将字符串转化为变量名的方法


头条面试题:实现一个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'));

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM