小兔网

这次给大家带来怎样使用js解析数据库(附代码),使用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[]

相信看了本文案例你已经掌握了方法,更多精彩请关注小兔网其它相关文章!

推荐阅读:

JS封装淡入淡出功能函数

webpack.config.js参数使用教程

以上就是怎样使用js解析数据库(附代码)的知识。速戳>>知识兔学习精品课!