安全读取对象中的未知数据,防止报错
简化版
function safe(obj, str, df) {
if (arguments.length !== 3) return false
if (!(typeof obj === 'object' && obj && typeof str === 'string' && str)) return df
let newObj = obj, arr = str.split('.')
for (let i = 0; i < arr.length; i++) {
if (newObj[arr[i]] === undefined) return df
if (newObj[arr[i]] === null || !(typeof newObj[arr[i]] === 'object' && arr[i] in newObj)) return i === arr.length - 1 ? newObj[arr[i]] : df
newObj = newObj[arr[i]]
}
return newObj
}
完整版
function safe(obj, str, df) {
if (arguments.length !== 3) return false
if (typeof obj === 'object' && obj && typeof str === 'string' && str) {
let newObj = obj
let arr = str.split('.')
for (let i = 0; i < arr.length; i++) {
if (newObj[arr[i]] === undefined) return df
if (newObj[arr[i]] === null) return i === arr.length - 1 ? newObj[arr[i]] : df
if (typeof newObj[arr[i]] === 'object' && arr[i] in newObj) {
newObj = newObj[arr[i]]
} else {
if (i === arr.length - 1) {
return newObj[arr[i]]
} else {
return df
}
}
}
return newObj
}
return df
}