2 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超6個(gè)贊
如果傳入的參數(shù)約定好,獲取內(nèi)部的值時(shí),屬性是按從外往內(nèi),用.連接起來(lái)的字符串。那么就在test()內(nèi)部,把參數(shù)str拆分開(kāi),從外向內(nèi)依次尋找即可:
function test(obj, str){
let params = str.split('.'), // 拆分
len = params.length,
item = obj;
for(let i=0; i<len; i++){
item = item[params[i]]
if( !item ){
return 'not found';
}
}
return item;
}
執(zhí)行:
var a = {
result: {
item: [1,2]
}
}
test(a, 'result.item'); // [1, 2]
var a = {
result: []
}
test(a, 'result.item'); // "not found"
test(a, 'result'); // []
var a = {
other: []
}
test(a, 'other'); // []
test(a, 'result'); // "not found"

TA貢獻(xiàn)1835條經(jīng)驗(yàn) 獲得超7個(gè)贊
preact源碼里有這樣的一個(gè)函數(shù),可參考let delve = (obj, key) => (key.split('.').map(p => (obj = obj && obj[p])), obj);
添加回答
舉報(bào)