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