想要拿到host
需要判断 config
是否存在再判断config.db
最后才能拿到config.db.host
非常难受
function main(config) {
let dbHost = config && config.db && config.db.host
console.log(dbHost); //127.0.0.1
}
main({
db:{
host:'127.0.0.1',
username:'locelhost'
},
cache:{
host:'https://www.cnblogs.com/Lucky-daisy',
username:'daisy'
},
})
使用ES11的可选链操作符 ?.
直接在链式调用的时候判断,左侧的对象是否为null
或undefined
。如果是,就不再往下运算,直接返回undefined
非常好用
function main(config) {
let dbHost = config?.db?.host
console.log(dbHost); //127.0.0.1
}
main({
db:{
host:'127.0.0.1',
username:'locelhost'
},
cache:{
host:'https://www.cnblogs.com/Lucky-daisy',
username:'daisy'
},
})