Usage of JS double question mark (??) and question mark point (?.)

1. Double question mark (??)

value1 ?? value2

?? Take a value between value1 and value2, only take value2 when value1 is null or undefined, otherwise take value1 (0, false, "" is considered meaningful, so take value1)

const obj = {}
console.log(obj.c ?? 'd') // 'd'
console.log(1 ?? "xx")			// 1
console.log(0 ?? "xx") 			// 0
console.log(null ?? "xx") 		// xx
console.log(undefined ?? "xx")  //xx
console.log(-1 ?? "xx") 		// -1
console.log("" ?? "xx") 		// ''

2. Question mark point (?.)

When accessing multi-layer object properties (such as res.data.list), if the property res.data is empty, a reference error will be reported, so we have to deal with it like this:

let dataList = res && res.data && res.data.list

It looks very ugly, the new syntax introduced today is to solve this problem (optional chain operator?.)

With optional chaining, you can safely reference a null or undefined property:

let dataList = res?.data?.list

The function is to judge whether (length) under (value) under (businessObject) under this object (this.element) is null or undefined, and return undefined when one of the links is null or undefined, so that even if there is a missing attribute in the middle No error will be reported, and the default value is followed by the double question mark.

Example 1 :

var obj ={}
console.log(obj ?. a ?. b)	// undefined
console.log(obj ?. a ?. b ?? 88 ) // 88
console.log(obj)	// Object {}
console.log(obj.a)	// undefined
console.log(obj.a.b)	// 报错

Example 2 :

var obj={a:{b:1}}
console.log(obj.a.b) // 1
console.log(obj ?. a ?. b ?? 66)	// 1
console.log(obj ?. a ?. c ?? 66) // 66
console.log(obj)	// {a:{b:1}}
console.log(obj.a)	// {b:1}

Guess you like

Origin blog.csdn.net/xijinno1/article/details/132095042