
使用#来定义私有属性
#count 是私有变量,不能通过 IncreasingCounter 实例访问
class IncreasingCounter {
#count = 0;
get value(){
console.log( ' Getting the current value!');
return this.#count++
}
}
子类可省略super(args);
class Animal {
constructor(name) {
this.name = name;
}
}
class Cat extends Animal {
constructor(name) {
super(name);
this.likesBaths =false;
}
meow() {
console.log('Meow!');
}
}
super() 这种在子类构造函数中模板式的写法可以不用了
class Cat extends Animal {
likesBaths = false;
meow() {
console.log('Meow!');
}
}
字符串新增 matchAll 方法
在 matchAll 出现之前,通过在循环中调用regexp.exec或string.match来获取所有匹配项信息
const regexp = RegExp('fo*','g');
const str = 'table football, foosball';
while ((matches = regexp.exec(str)) !== null) {
console.log(matches[0]);
}
const str = 'table football, foosball';
const regex = /fo*/gu ;
for (const match of str . match( regex)) {
console . log(match)
};
使用string.matchAll
const regexp = RegExp('foo*','g');
const str = 'table football, foosball';
let matches = str.matchAll(regexp);
for (const match of matches) {
console.log(match);
}
使用matchAll 的另外一个亮点是更好地获取分组捕获。因为当使用match()和/g标志方式获取匹配信息时,分组捕获会被忽略:
const string = 'Favorite GitHub repos: tc39/ecma262 v8/v8.dev';
const regex = /\b(?<owner>[a-z0-9]+)\/(?<repo>[a-z0-9\.]+)\b/g;
for (const match of string.matchAll(regex)) {
console.log(`${match[0]} at ${match. index} with '${match.input}'`);
console.log(`owner: ${match.groups.owner}`);
console.log(`repo: ${match.groups.repo}`);
}
BigInt进行大数字计算
大数据字,如 1234567890123456789 * 123 计算不了?js不存在了
1234567890123456789n * 123n;
//151851850485185185047n V
array.flat和array.flatMap
// Flatten one level :
const array = [1, [2, [3]]];
array. flat( ) ;// [1, 2, [3] ]
//Flatten recursively until the array contains no
// more nested arrays :
array . flat( Infinity) ;// [1,2,3]
//flatMap
const duplicate = (x) => [x, x] ;
[2, 3, 4] . map( duplicate) . flat();// [2, 2, 3,3, 4, 4]
// use flatMap will be more simple
[2, 3, 4]. flatMap( duplicate) ;// [2,2,3,3,4,4]
array.sort稳定排序
对数组的元素进行排序,并返回数组。排序算法现在是稳定的了!
Object.fromEntries
const object = {x:42,y:50};
const entries = Object . entries( object) ;// [['x', 42], ['y', 50]]
const result = Object. fromEntries(entries) ;// {x:42,y:50}
const map=new Map(entries);
//Convert the map back into an object;
const objectCopy=Object.fromEntries(map);
获取全局对象
下面的代码可以不需要了
const getGlobalThis = ( ) =>
{
if ( typeof self !== ' undefined' ) return self ;
if ( typeof window !== ' undefined') return window ;
if ( typeof global !=='undefined') return global ;
if ( typeof this!=='undefined') return this ;
throw new Error('Unable to locate global object') ;
};
使用这个吧
const theGlobalThis = globalThis;
在最外层使用await
之前,await必须要放在async函数中执行,如果要在最外层使用,得像这样
//在最外层执行await
( async function() {
const result = await doSomethingAsync() ;
doSomethingElse( );
})();
现在不用了
const result = await doSomethingAsync() ;
doSomethingElse( );
增Promise.allSettled,Promise.any
Promise.all 和Promise.race会因为reject中断,如果不希望这样,可以使用Promise.allSettled,Promise.any 替代。
WeakRef
WeakMap 仅支持 object 类型作为 Key 的场景,·并且不能遍历。WeakRef 封装的对象将为弱引用,可以将这个对象赋值给其它变量。如睛,ref为WeakMap对像,当其封装的对象不存在时,ref也会被回收;
const cache =new Map();
function getImageCached(name ) {
letref = cache.get(name);
if (ref !== undefined) {
const deref = ref.deref();
if (deref !== undefined) return deref;
const image = performExpensiveOperation(name);
ref = new WeakRef(image);
cache.set(name, ref);
return image;
}
}
那保存WeakMap对象的变量怎么回收呢,解决方案是引入一个新的 API FinalizationGroup()。在FinalizationGroup上注册一个回调函数,用来在 GC 触发时从缓存中删除这些变量。
const cache = new Map();
const finalizationGroup = new FinalizationGroup((iterator) => {
for (const name of iterator) {
const ref = cache.get(name);
if (ref !== undefined && ref.deref() === undefined) {
cache.delete(name);
}
}
});
本地化接口 Intl
Intl 是 ECMAScript 国际化 API 的一个命名空间,它提供了精确的字符串对比、数字格式化,和日期时间格式化。
可参考这里:
developer.mozilla.org/zh-CN/docs/…
特别提到了Intl.RelativeTimeFormat,感受下吧
var rtf1 = new Intl.RelativeTimeFormat('zh', { style: 'narrow' });
console.log(rtf1.format(3, 'quarter'));
//"3个季度后"
console.log(rtf1.format(-1, 'day'));
//"1天前"
var rtf2 = new Intl.RelativeTimeFormat('zh', { numeric: 'auto' });
console.log(rtf2.format(2, 'day'));
//"后天"