ES6+ 新特性

ES2020 (ES11)

  • 可选链运算符 - Optional Chaining

有时候为了访问深层嵌套的属性,我们需要写一个很长的&&链去检查每个属性是否存在,代码如下:

var price = result && result.body && result.body.data && result.body.data.price;

事实上在日常开发中我们经常要这么做,而且如果我们不这么做,那么很可能导致程序异常。为了简化上述的代码,于是乎新增了可选链运算符,代码如下:

var price = result?.body?.data?.price;

  • 空值合并运算符 - Nullish coalescing Operator

获取对象的属性的时候,我们经常需要为 null/undefined 的属性设置默认值。目前正常的情况下我们可以使用 || 运算符,例如:

var user = {}; 
var name = user.name || 'p9';

但是,这么做会导致false,0,空字符串等属性会被覆盖掉,这是我们不愿意看到的,这时候就可以使用空值合并运算符来避免。例如:

const obj = {a:null,b:undefined,c:0,d:false,e:''}
obj.a ?? 10 // 10
obj.b ?? 10 // 10
obj.c ?? 10 // 0
obj.d ?? 10 // false
obj.e ?? 10 // ""
  • 标准的方式去获取不同环境下的全局对象:globalThis。例如:

function canMakeHTTPRequest() {
    return typeof globalThis.XMLHttpRequest === 'function';
}

console.log(canMakeHTTPRequest());
// expected output (in a browser): true
  • Promise.allSettled

const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));
const promises = [promise1, promise2];

Promise.allSettled(promises).
  then((results) => results.forEach((result) => console.log(result)));

//  [{
//   "status": "fulfilled",
//   "value": 3
//  },
//  {
//   "status": "rejected",
//   "reason": "foo"
//  }]
  • 异步加载模块 - import()

// log.js
export default {
  log: function() {
      console.log(...arguments);
  }
};

// log.html
<script type="text/ecmascript">
  import('./log.js').then((module)=>{
    module.default.log(200) // 200
  })
</script>

当然,也可以使用await进行同步请求

let module = await import('/modules/my-module.js');

 


ES2019(ES10)

ES2018(ES9)

ES2017(ES8)

ES2016(ES7)

原文地址:https://www.cnblogs.com/it-Ren/p/14651265.html