ECMAScript新特性概览

ES2021(ES12)

String.prototype.replaceAll

replaceAll() 返回一个新字符串,其中模式的所有匹配都会被替代项替换。模式可以是字符串或正则表达式,而替换项可以是字符串或针对每次匹配执行的函数。

letstr='Iuselinux,Ilovelinux'str=str.replaceAll('linux','windows');
console.log(str)
/****Output****///Iusewindows,Ilovewindows

Promise.any

只要这个方法命中了 Promise 列表 / 数组中的第一个已解析的 Promise,就会短路并返回一个值,它与 Promise.race() 不同,因为一旦给定的 Promise 之一被解析或拒绝,Promise.any() 方法就会短路。

Promise.any([
newPromise((resolve,reject)=>setTimeout(reject,200,'Third')),
newPromise((resolve,reject)=>setTimeout(resolve,1000,'Second')),
newPromise((resolve,reject)=>setTimeout(resolve,2000,'First')),
])
.then(value=>console.log(`Result:${value}`))
.catch(err=>console.log(err))
/****Output****///Result:Second

带有 && 运算符的逻辑赋值运算符

仅当 LHS 值为真时,才将 RHS 变量值赋给 LHS 变量。

//LogicalAssignmentOperatorwith&&operator
letnum1=5
letnum2=10num1&&=num2
console.log(num1)//10
//Line5canalsobewrittenasfollowingways
//1.num1&&(num1=num2)
//2.if(num1)num1=num2

带有||的运算符逻辑赋值运算符

仅当 LHS 值为假时,才将 RHS 变量值赋给 LHS 变量。

//LogicalAssignmentOperatorwith||operator
letnum1
letnum2=10num1||=num2
console.log(num1)//10
//Line5canalsobewrittenasfollowingways
//1.num1||(num1=num2)
//2.if(!num1)num1=num2

带有?? 运算符的逻辑赋值运算符

仅当 LHS 为 undefined 或仅为 null 时,才将 RHS 变量值赋给 LHS 变量。

//LogicalAssignmentOperatorwith??operator
letnum1
letnum2=10num1??=num2
console.log(num1)//10
num1=falsenum1??=num2
console.log(num1)//false
//Line5canalsobewrittenasfollowingways
//num1??(num1=num2)

数值分隔符

新引入的数值分隔符使用 _(下划线)字符,在数值组之间提供分隔,使数值读起来更容易。

letnumber=100_000console.log(number)
/****Output****/
//100000

Intl.ListFormat

ListFormat 对象带有两个参数,它们都是可选的。第一个参数是语言(语言环境),第二个参数是具有两个属性(样式和类型)的选项对象。

newIntl.ListFormat([locales[,options]])

Intl.ListFormat 有一个称为 format() 的方法,该方法接收一个数组作为一个参数,并以特定于语言环境的方式对其进行格式化

constarr=['Pen','Pencil','Paper']
letobj=newIntl.ListFormat('en',{style:'short',type:'conjunction'})
console.log(obj.format(arr))
/****Output****/
//Pen,Pencil,&Paper
obj=newIntl.ListFormat('en',{style:'long',type:'conjunction'})
console.log(obj.format(arr))
/****Output****/
//Pen,Pencil,andPaper
obj=newIntl.ListFormat('en',{style:'narrow',type:'conjunction'})
console.log(obj.format(arr))
/****Output****/
//Pen,Pencil,Paper
//传递意大利语标签
obj=newIntl.ListFormat('it',{style:'short',type:'conjunction'})
console.log(obj.format(arr))
/****Output****/
//Pen,PencilePaper
//德语标签传递
obj=newIntl.ListFormat('de',{style:'long',type:'conjunction'})
console.log(obj.format(arr))
/****Output****/
//Pen,PencilundPaper

dateStyle 和 timeStyle 选项

Intl.DateTimeFormat 对象是用来启用语言敏感的日期和时间格式的对象构造器。新提案的 dateStyle 和 timeStyle 选项可用于请求给定长度的,特定于语言环境的日期和时间。

//时间仅限于短格式
leto=newIntl.DateTimeFormat('en',{timeStyle:'short'})
console.log(o.format(Date.now()))
//11:27PM
//仅限中等格式的时间
o=newIntl.DateTimeFormat('en',{timeStyle:'medium'})
console.log(o.format(Date.now()))
//11:27:57PM
//只有长格式的时间
o=newIntl.DateTimeFormat('en',{timeStyle:'long'})
console.log(o.format(Date.now()))
//11:27:57PMGMT+11
//仅限短格式日期
o=newIntl.DateTimeFormat('en',{dateStyle:'short'})
console.log(o.format(Date.now()))
//10/6/20
//仅限中等格式的日期
o=newIntl.DateTimeFormat('en',{dateStyle:'medium'})
console.log(o.format(Date.now()))
//Oct6,2020
//仅限长格式的日期
o=newIntl.DateTimeFormat('en',{dateStyle:'long'})
console.log(o.format(Date.now()))
//October6,2020

dateStyle 和 timeStyle 选项与不同的语言标记一起使用

letabc
//Englishlanguage
abc=newIntl.DateTimeFormat('en',{timeStyle:'short',dateStyle:'long'})
console.log(abc.format(Date.now()))
//October6,2020at11:40PM
//Italianlanguage
abc=newIntl.DateTimeFormat('it',{timeStyle:'short',dateStyle:'long'})
console.log(abc.format(Date.now()))
//6ottobre202023:40
//Germanlanguage
abc=newIntl.DateTimeFormat('de',{timeStyle:'short',dateStyle:'long'})
console.log(abc.format(Date.now()))
//6.Oktober2020um23:40

ES2020(ES11)

动态import

import('/modules/my-module.js')
.then((module)=>{
//Dosomethingwiththemodule.
});
letmodule=awaitimport('/modules/my-module.js');

空值合并运算符

ES2020 引入了一个新的运算符 ??,该运算符的工作原理与短循环类似,但仅当初始值为 null 或 undefined 时才读取为运算符右边的值

constnullValue=null;
constemptyText="";//falsy
constsomeNumber=42;
constvalA=nullValue??"defaultforA";
constvalB=emptyText??"defaultforB";
constvalC=someNumber??0;
console.log(valA);//"defaultforA"
console.log(valB);//""(astheemptystringisnotnullorundefined)
console.log(valC);//42

可选链接

可选的链接运算符 ?. 允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。运算符的功能与 .chaining 运算符相似,不同之处在于,如果引用为空(null 或 undefined),则表达式会短路,返回值为 undefined。当与函数调用一起使用时,如果给定的函数不存在,则返回未定义的值。

constuser={name:"John"};
//Failswith`UncaughtTypeError:Cannotreadproperty'city'ofundefined`
constcity=user.address.city;
//Worksbutverbose
letcity="NotSet";
if(user.address!==undefined&&user.address!==null){
city=user.address.city;
}
//Worksandconcisebutrequiresa3rdpartylibrary
constcity=_.get(user,"address.city","NotSet");
//🤗
constcity=user?.address?.city??"NotSet";

Promise.allSettled

返回一个在所有给定的promise都已经fulfilled或rejected后的promise,并带有一个对象数组,每个对象表示对应的promise结果

constpromise1=Promise.resolve(3);
constpromise2=newPromise((resolve,reject)=>setTimeout(reject,100,'foo'));
constpromises=[promise1,promise2];
Promise.allSettled(promises).
then((results)=>results.forEach((result)=>console.log(result.status)));
//expectedoutput:
//"fulfilled"
//"rejected"

String.prototype.matchAll

返回一个包含所有匹配正则表达式的结果及分组捕获组的迭代器。

constregexp=/t(e)(st(\d?))/g;
conststr='test1test2';
constarray=[...str.matchAll(regexp)];
console.log(array);
//expectedoutput:Array[Array["test1","e","st1","1"],Array["test2","e","st2"
    ,"2"]]
    ```
## BigInt
BigInt 是一个内置的对象,它提供了一种方法来表示大于 2⁵³-1 的整数,这是 JavaScript 可以可靠地用 number 原语表示的最大数,并由 number 表示。MAX_SAFE_INTEGER 常量。BigInt 可用于任意大整数。
## globalThis
全局globalThis属性包含this类似于全局对象的全局值。
```javascript
if(typeofglobalThis.setTimeout!=='function'){
//nosetTimeoutinthisenvironment!
}

ES2019(ES10)

Array.prorptype.flat

方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。

constarr1=[0,1,2,[3,4]];
console.log(arr1.flat());
//expectedoutput:[0,1,2,3,4]
constarr2=[0,1,2,[[[3,4]]]];
console.log(arr2.flat(2));
//expectedoutput:[0,1,2,[3,4]]

Array.prorptype.flatMap

方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。

vararr1=[1,2,3,4];
arr1.map(x=>[x*2]);
//[[2],[4],[6],[8]]
arr1.flatMap(x=>[x*2]);
//[2,4,6,8]
//onlyonelevelisflattened
arr1.flatMap(x=>[[x*2]]);
//[[2],[4],[6],[8]]

String.prototype.trimStart

方法从字符串的开头删除空格。trimLeft() 是此方法的别名。

constgreeting='Helloworld!';
console.log(greeting);
//expectedoutput:"Helloworld!";
console.log(greeting.trimStart());
//expectedoutput:"Helloworld!";

String.prototype.trimEnd

方法从字符串的结尾删除空格。trimLeft() 是此方法的别名。

constgreeting='Helloworld!';
console.log(greeting);
//expectedoutput:"Helloworld!";
console.log(greeting.trimEnd());
//expectedoutput:"Helloworld!";

Object.fromEntries()

把键值对列表转换为一个对象。

constentries=newMap([
['foo','bar'],
['baz',42]
]);
constobj=Object.fromEntries(entries);
console.log(obj);
//expectedoutput:Object{foo:"bar",baz:42}

Symbol.prototype.description

是一个只读属性,它会返回 Symbol 对象的可选描述的字符串。

console.log(Symbol('desc').description);
//expectedoutput:"desc"
console.log(Symbol.iterator.description);
//expectedoutput:"Symbol.iterator"
console.log(Symbol.for('foo').description);
//expectedoutput:"foo"
console.log(`${Symbol('foo').description}bar`);
//expectedoutput:"foobar"

ES2018(ES9)

rest / spread

属性允许将对象的剩余属性收集到新对象中

constobj={foo:1,bar:2,baz:3};
const{foo,...rest}=obj;
//constfoo=1;
//constrest={bar:2,baz:3};

for-await-of

异步或者同步可迭代对象上创建一个迭代循环

forawait(variableofiterable){
statement
}

Promise.prototype.finally

返回一个Promise。在promise结束时,无论结果是fulfilled或者是rejected,都会执行指定的回调函数。这为在Promise是否成功完成后都需要执行的代码提供了一种方式

p.finally(onFinally);
p.finally(function(){
//返回状态为(resolved或rejected)
});

正则表达式

?= 先行断言(lookahead)/test(?=\d)/.test('test1') => true
?! 先行断言逆操作:/test(?!\d)/.test('test1') => false
?<= 后行断言(lookbehind)/(?<=Roger) Waters/.test('Roger Waters') => true
?<! 后行断言逆操作:/(?<!Roger) Waters/.test('Roger Waters') => false
命名捕获组: const result = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/.test('2018-01-01') => result.groups.year
s 标志 single line,使 . 符号可以匹配新行:/hi.+tom/s.test('hi,\ntom') => true
使用 Unicode 属性转义 \p{} 和 \P{} 扩展 Unicode 匹配范围:
/^\p{ASCII}+$/u.test('ABC&#x1f643;') => false
/^\p{Emoji}+$/u.test('&#x1f643;&#x1f643;') => true
/^\p{ASCII_Hex_Digit}+$/u.test('0123456789ABCDEF') => true
/^\p{Uppercase}$/u.test('H') => true
/^\p{Lowercase}$/u.test('h') => true
/^\p{Script=Latin}+$/u.test('hey') => true

ES2017(ES8)

’ '.padStart ’ '.padEnd

字符串补全长度

'x'.padEnd(4, 'ab') // 'xaba'
'x'.padEnd(5, 'ab') // 'xabab'

Object.values

返回一个给定对象自身的所有可枚举属性值的数组

var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.values(obj)); // ['a', 'b', 'c']

Object.entries

返回一个给定对象自身可枚举属性的键值对数组

const object1 = {
  a: 'somestring',
  b: 42
};
for (const [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}
// expected output:
// "a: somestring"
// "b: 42"

Object.getOwnPropertyDescriptors()

用来获取一个对象的所有自身属性的描述符。

Object.getOwnPropertyDescriptors(obj)

Async Functions 异步函数 Async/Await

构造函数用来创建新的 异步函数 对象,JavaScript 中每个异步函数都是 AsyncFunction 的对象。

async function asyncFunc() {
    const result1 = await otherAsyncFunc1();
    console.log(result1);
    const result2 = await otherAsyncFunc2();
    console.log(result2);
}

共享内存 和 Atomics

ES2016(ES8)

Array.prototype.includes

用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false。

const array1 = [1, 2, 3];
console.log(array1.includes(2));
// expected output: true
const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));
// expected output: true
console.log(pets.includes('at'));
// expected output: false

指数运算符 **

let a = 1.5;
a **= 2;
// 等同于 a = a * a;
let b = 4;
b **= 3;
// 等同于 b = b * b * b;
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值