您好,欢迎访问一九零五行业门户网

js解析数据技巧总结

这次给大家带来js解析数据技巧总结,js解析数据的注意事项有哪些,下面就是实战案例,一起来看一下。
自从有了前后端分离,一些后端小伙伴给出的数据结构也来越混乱了。以为分离减轻了他们的负担接口的质量会非常高但是人的惰性却体现的很“完美”。
由于js是若类型的语言,所以在使用数据的时候经常会出现这个几个错误
typeerror: cannot read property 'xxx' of undefined typeerror: cannot read property 'xxx' of null typeerror: 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 || '你没名字' } // 这是多么痛苦的一件事情 @后端兄弟 // 第二种,感谢es6 let {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]')) // 输出结果 undefined undefined 12312 [1, 2, 3] 2 undefined undefined []
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
jquery拖动文件上传加载添加进度条
js原型与原型链使用详解
以上就是js解析数据技巧总结的详细内容。
其它类似信息

推荐信息