【JS新特性】关于 可选链?. 与 空值合并运算符??

举例
let a = {a:"1",b:"2"}
console.log(a?.a)

契机:另一个组的同事在一个 angular 项目里发现了这个语法的使用,

之前查半天无果,便在v2ex自己发了帖子https://www.v2ex.com/t/663072?p=1

收获颇丰:

 

?.操作符,译为可选链,

MDN的科普链接为https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/%E5%8F%AF%E9%80%89%E9%93%BE

搬运介绍:“可选链操作符?.能够去读取一个被连接对象的深层次的属性的值而无需明确校验链条上每一个引用的有效性。?.运算符功能类似于.运算符,不同之处在于如果链条上的一个引用是nullish (null 或 undefined),.操作符会引起一个错误,?.操作符取而代之的是会按照短路计算的方式返回一个undefined。当?.操作符用于函数调用时,如果该函数不存在也将会返回undefined。 当访问链条上可能存在的属性却不存在时,?.操作符将会使表达式更短和更简单。当不能保证哪些属性是必需的时,?.操作符对于探索一个对象的内容是很有帮助的。”

搬运例子

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

 

??操作符,译为空值合并运算符,

MDN的科普链接为https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

搬运一下介绍:“由于 || 是一个布尔逻辑运算符,左侧的操作数会被强制转换成布尔值用于求值。任何假值( 0, '',NaN,null,undefined )都不会被返回。这导致如果你使用 0,''或 NaN 作为有效值,就会出现不可预料的后果.
空值合并操作符??可以避免这种陷阱,其只在第一个操作数为 null 或 undefined 时(而不是其它假值)返回第二个操作数。”

搬运例子

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

const baz = 0 ?? 42;
console.log(baz);
// expected output: 0

 

这些前卫的js写法,笔者被推荐关注了tc39:https://github.com/tc39/proposal-optional-chaining

而这个链接是es的stage4阶段的提案https://github.com/tc39/proposals/blob/master/finished-proposals.md

 

 

搜这些术语的英文的话,还是有结果的(比如搜索Nullish Coalescing找到了这篇文章http://www.fly63.com/article/detial/3434)

Optional Chaining(可选链式调用)

Nullish coalescing(空值合并)

Pipeline operator(管道运算符)

你可能感兴趣的:(javascript发现,前端,javascript,node.js)