這次帶給大家怎麼使用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中文網其他相關文章!