將字符串轉化為變量名的方法


頭條面試題:實現一個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