题目如下:
实现一个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']
下边给出我的解答:思路很简单,就是替换字符,然后再切割字符串
function doSomeThing(){
const obj = { selector: { to: { toutiao: "FE Coder"} }, target: [1, 2, { name: 'byted'}]}
this.get(obj, 'selector.to.toutiao', 'target[0]', 'target[2].name')
}
function get(){
let obj = arguments[0]
let temp = []
let res = []
for(let i=1;i<arguments.length;i++){
let x = (arguments[i].replace(/\[/g,'.')).replace(/\]/g,'')
temp.push(x)
}
for(let j=0;j<temp.length;j++){
let arr = temp[j].split('.')
let result = obj
for(let k=0;k<arr.length;k++){
result = result[arr[k]]
}
res.push(result)
}
console.log(res)
}