js中??和?.的意思

7/21/2021 es6

# js中??和?.的意思

空值合并操作符??

只有当左侧为null和undefined时,才会返回右侧的数

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

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

const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"

const baz = 0 ?? 42;
console.log(baz);
// expected output: 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

可选链操作符( ?. )

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

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined

console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined
语法: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];
例子:
    let myMap = new Map();
    myMap.set("foo", {name: "baz", desc: "inga"});

    let nameBar = myMap.get("bar")?.name;
    在一个不含 bar 成员的 Map 中查找 bar 成员的 name 属性,因此结果是 undefined。
短路计算:
let potentiallyNullObj = null;
let x = 0;
let prop = potentiallyNullObj?.[x++];

console.log(x); // x 将不会被递增,依旧输出 0

当在表达式中使用可选链时,如果左操作数是 null 或 undefined,表达式将不会被计算
连用可选链操作:
let customer = {
  name: "Carl",
  details: {
    age: 82,
    location: "Paradise Falls" // details 的 address 属性未有定义
  }
};
let customerCity = customer.details?.address?.city;

// … 可选链也可以和函数调用一起使用
let duration = vacations.trip?.getTime?.();
空值合并操作符可以在使用可选链时设置一个默认值:

let customer = {
  name: "Carl",
  details: { age: 82 }
};

let customerCity = customer?.city ?? "暗之城";
console.log(customerCity);  // “暗之城”
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
Last Updated: 8/1/2021, 5:24:42 PM