js中的 可选链操作符、空值合并操作符、空值赋值运算符、非空断言操作符

1.可选链操作符( ?. )

const adventurer = {
  name: 'Alice',
  fish: {
    name: 'Dinah'
  }
};
const dogName = adventurer.cat?.name;
console.log(dogName);// undefined
 
console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined

可选链操作符( ?. )允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。?. 操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空(null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值

let a;
let b = a?.name;


只有当a存在,同时a具有name属性的时候,才会把值赋给b,否则就会将undefined赋值给b.重要的是,不管a存在与否,这么做都不会报错.

语法:obj?.prop  obj?.[expr]   arr?.[index]   func?.(args)

// 函数调用
let result = someInterface.customMethod?.();
如果希望允许 someInterface 也为 null 或者 undefined ,那么你需要像这样写 someInterface?.customMethod?.()

可选链与表达式: 

let nestedProp = obj?.['prop' + 'Name'];

可选链访问数组:

let arrayItem = arr?.[42];


2.空值合并操作符(??)
空值合并操作符(??)是一个逻辑操作符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。

  与逻辑或操作符(||)不同,逻辑或操作符会在左侧操作数为假值时返回右侧操作数。也就是说,如果使用 || 来为某些变量设置默认值,可能会遇到意料之外的行为。比如为假值(例如,'' 或 0)时。

const food = null ?? 'default string';
console.log(food);  // "default string"
 
const cfz = 0 ?? 42;
console.log(cfz);  //  0
const nullValue = null;
const emptyText = ""; // 空字符串,是一个假值,Boolean("") === false
const someNumber = 42;
 
const valA = nullValue ?? "valA 的默认值";
const valB = emptyText ?? "valB 的默认值";
const valC = someNumber ?? 0;
 
console.log(valA); // "valA 的默认值"
console.log(valB); // ""(空字符串虽然是假值,但不是 null 或者 undefined)
console.log(valC); // 42

空值合并操作符可以在使用可选链时设置一个默认值:

let customer = {
  name: "kite",
  details: { kg: 56 }
};
 
let custom = customer?.city ?? "CFZ";
console.log(custom);  // “CFZ”

3.空值赋值运算符(??=)
当??=左侧的值为null、undefined的时候,才会将右侧变量的值赋值给左侧变量.其他所有值都不会进行赋值.同样在一些场景下,可以省略很多代码.

let b = 'hello';
let a = 0
b ??= a;     // b = “hello”
 
let c = null;
let d = ’123‘
c ??= d      // c = '123'

4. 非空断言操作符(!.)
这是TypeScript的语法,叫非空断言操作符(non-null assertion operator),和?.相反,这个符号表示对象后面的属性一定不是null或undefined。

let name:string = 'kite'
 
console.log(name!.trim())

————————————————
版权声明:本文为CSDN博主「kite吖」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_44376306/article/details/123068955

猜你喜欢

转载自blog.csdn.net/w1311004532/article/details/128398399