亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

js對象如何優雅的取一個深度的值?

js對象如何優雅的取一個深度的值?

ibeautiful 2018-08-28 13:22:27
問題描述比如后臺可能返回一個對象let obj = {     school: {       class1: {         student: 50       }     } }我需要取出里面student的值,但是有可能后臺返回給我的是 {school: null} 或者 {} 甚至是 undefined因此我取值時可能是let student = obj?(obj.school?(obj.school.class1?(obj.school.class1.studnet?obj.school.class1.studnet:''):''):''):'';這顯然可讀性不好,也麻煩,請問有什么方式可以優雅的處理這種取值并且防止Cannot read property 'xxx' of undefined 的報錯嗎
查看完整描述

2 回答

?
慕斯王

TA貢獻1864條經驗 獲得超2個贊

function safeProps(func, defaultVal) {

    try {

        return func();

    } catch (e) {

        return defaultVal;

    }

}


safeProps(function(){

    student = obj.school.class1.student

}, -1)


查看完整回答
反對 回復 2018-09-06
?
海綿寶寶撒

TA貢獻1809條經驗 獲得超8個贊

如果不用考慮兼容性的話,加個Proxy監聽get是個很合適的辦法

/**

 * @param target

 * @param exec 取值屬性

 * @returns {*}

 */

function getter(target, exec = '_') {

  return new Proxy({}, {

    get: (o, n) => {

      return n === exec ?

        target :

        getter(typeof target === 'undefined' ? target : target[n], exec)

    }

  });

}


let obj = {

  school: {

    class1: {

      student: 50

    }

  }

};


console.log(getter(obj).school.class1.student._)//50

console.log(getter(obj).school1.class11.student._)//undefined


查看完整回答
反對 回復 2018-09-06
  • 2 回答
  • 0 關注
  • 1461 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號