es6链判断运算符和null的判断运算符

链判断运算符

JavaScript在实际编程中,如果读取对象内部的某个属性,往往需要判断一下。

需要判断属性的上层对象是否存在。比如,读取 dataList.userInfo.firstName这个属性,安全的写法是写成下面这样。

let dataList={
    
    
	userInfo:{
    
    
		firstName:''
	}
}
// 错误的写法;因为这dataList.userInfo这个值可能没有,会导致报错
const  firstName = dataList.userInfo.firstName || 'default';
// 正确的写法
const firstName = (dataList && dataList.userInfo && dataList.userInfo.firstName) || 'default';

这样写会觉得很繁琐,有没有什么办法能改简化写法呢?答案肯定是有的,那就是使用链式运算符,具体写法如下:

//使用链式运算符
let firstName = dataList ?.userInfo?.firstName || '默认值';
/**
 * 上面代码中,如果dataList是null或undefined,`在这里插入代码片`
 * 或者dataList.userInfo是null或undefined,
 * 或者dataList.userInfo.firstName是null或undefined.
 * 就会返回--默认值。
 * */

链判断运算符(?.)的详细讲解

  • ?.运算符,直接在链式调用的时候判断。
  • 左侧的对象是否为null或undefined。
  • 如果是的,就不再往下运算,而是返回undefined
  • 本质上,?.运算符相当于一种短路机制,只要不满足条件,就不再往下执行。

链判断运算符-判断对象是否有某个方法

let message={
    
    
// say:function(){
    
    
//    console.log('hello word')
// }
}
//如果没有该方法,则不会被执行的哈
message.say?.() 
//返回undefined
console.log(message.say?.())

null的判断运算符

读取对象属性的时候,如果某个属性的值是null或undefined,有时候需要为它们指定默认值。常见做法是通过||运算符指定默认值。

const headerText = response.settings || 'Hello, world!';
const animationDuration = response.settings || 300;

但是我们开发者的意愿是:只要属性的值为nullundefined,默认值就会生效,但是实际属性的值如果为空字符串或false0,默认值也会生效。(与我们的初衷相违背)

为了避免这种情况,ES2020 引入了一个新的 Null 判断运算符??。它的行为类似||,但是只有运算符左侧的值为nullundefined时,才会返回右侧的值。

const headerText = response.settings ?? 'Hello, world!';
const animationDuration = response.settings ?? 300;

上面代码中,默认值只有在左侧属性值为nullundefined时,才会生效。

const animationDuration = response.settings?. animationDuration ?? 300;

上面代码中,如果response.settings是null或undefined,或者response.settings.animationDuration是null或undefined,就会返回默认值300。也就是说,这一行代码包括了两级属性的判断。

Guess you like

Origin blog.csdn.net/baidu_39009276/article/details/126579237