自從有了前后端分離,一些后端小伙伴給出的數據結構也來越混亂了。以為分離減輕了他們的負擔接口的質量會非常高但是人的惰性卻體現的很“完美”。
由于js是若類型的語言,所以在使用數據的時候經常會出現這個幾個錯誤
TypeError: Cannot read property 'xxx' of undefinedTypeError: Cannot read property 'xxx' of nullTypeError: xxx.map is not a function
而這些異常很難發現,及時發上線了都不一定能發現。因為這些問題都是由于數據異常導致的。如果優雅的解決或者說避免這些問題影響到用戶體驗呢?
// 第一種做法肯定是這樣的if(a){ return a.name || '你沒名字'}// 這種做法處理簡單的還能湊合用,但是如果你遇到這樣的呢 user.country.area.city.name,難道要這樣寫if(user && user.country && user.country.area && user.country.area.city){ return user.country.area.city.name || '你沒名字'}// 這是多么痛苦的一件事情 @后端兄弟// 第二種,感謝es6let {country={area:{city:{name:'你沒名字'}}}} = user;這個感覺也不是很好的解決方案// 第三種,利用reduce構建一個解析函數function getValue(obj,key){ return key.split('.').reduce(function(o,k){ // o,當前對象 // key,數組下一個元素 if((typeof o === 'undefined' || o === null)){ return k.indexOf('[array]') !== -1?[]:o }else{ return k.indexOf('[array]') !== -1?(o[k.replace('[array]','')]||[]):o[k] } },obj)}let user1;let user2 = { }let user3 = { country:{ area:{ city:{ name:'12312' } } }}let user4 = { country:[ { city:{ name:'12312' } } ]}let user5 = { country:{ city:[1,2,3] }}console.log(getValue(user1,'country.area.city.name'))console.log(getValue(user2,'country.area.city.name'))console.log(getValue(user3,'country.area.city.name'))console.log(getValue(user5,'country.city[array]'))console.log(getValue(user5,'country.city[array].1'))console.log(getValue(user5,'country.city[array].10'))console.log(getValue(user5,'country.city[array].1.name'))console.log(getValue(user5,'country.city[array].persion[array]'))// 輸出結果undefinedundefined"12312"[1, 2, 3]2undefinedundefined[]
代碼測試:https://jsbin.com/zoberem/edit?js,console
最后關于前端異常上報,這是一個很大的研究方向,市面上也有一些解決方案,但是真正推廣的我目前沒發現。
新聞熱點
疑難解答