这次给大家带来怎样使用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
[]相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
以上就是怎样使用js解析数据库(附代码)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号