博客
关于我
可选链操作符 ?.
阅读量:585 次
发布时间:2019-03-11

本文共 627 字,大约阅读时间需要 2 分钟。

function main(config){   	const dbHost = config && config.db && config.db.host;	console.log(dbHost)}main({   	db:{   		host:'192.168.20.60',		userName:'liuy'	},	cache:{   		host:'192.168.20.80',		userName:'admin'	}})

使用链式操作符之前,我们使用上面代码进行判断,判断是否传了config ,如果传了,判断是否传入config.db,再判断是否传入了host。如果不判断就会报错。

使用链式操作符来判断,如下:

function main(config){   	const dbHost = config?.db?.host;	console.log(dbHost)}main({   	db:{   		host:'192.168.20.60',		userName:'liuy'	},	cache:{   		host:'192.168.20.80',		userName:'admin'	}})

在这里插入图片描述

即便是不传,也不会报错

function main(config){   	const dbHost = config?.db?.host;	console.log(dbHost)}main()

在这里插入图片描述

可选链操作符 ?.是ES11的新特性。

转载地址:http://heftz.baihongyu.com/

你可能感兴趣的文章
NativePHP:使用PHP构建跨平台桌面应用的新框架
查看>>
nativescript(angular2)——ListView组件
查看>>
NativeWindow_01
查看>>