第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

字符串object變量解析問(wèn)題

字符串object變量解析問(wèn)題

a可能是這樣var a = {    result: {        item: [1,2]    }}也可能是這樣var a = {    result: []}也可能是這樣var a = {    other: []}我要封裝根據(jù)字符串來(lái)找到a對(duì)應(yīng)key的value值// 這個(gè)str傳有可能是'result', 'result.items', 'other'function test (str) {    // a[str] ???}// 那么我這里這么寫(xiě)才能使得上面的object a['變量']解析出來(lái)呢?
查看完整描述

2 回答

?
30秒到達(dá)戰(zhàn)場(chǎng)

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"


查看完整回答
反對(duì) 回復(fù) 2019-03-04
?
qq_花開(kāi)花謝_0

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);

查看完整回答
反對(duì) 回復(fù) 2019-03-04
  • 2 回答
  • 0 關(guān)注
  • 540 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)