Google I/O 2019上提及的Javascript新特性

栏目: JavaScript · 发布时间: 7年前

内容简介:##字符串新增 matchAll 方法 在 matchAll 出现之前,通过在循环中调用
Google I/O 2019上提及的Javascript新特性

##使用#来定义私有属性

#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.any 会因为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'));
//"后天"
复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

复杂网络理论及其应用

复杂网络理论及其应用

汪小帆、李翔、陈关荣 / 清华大学出版社 / 2006 / 45.00元

国内首部复杂网络专著 【图书目录】 第1章 引论 1.1 引言 1.2 复杂网络研究简史 1.3 基本概念 1.4 本书内容简介 参考文献 第2章 网络拓扑基本模型及其性质 2.1 引言 2.2 规则网络 2.3 随机图 2.4 小世界网络模型 2.5 无标度网络模型 ......一起来看看 《复杂网络理论及其应用》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

SHA 加密
SHA 加密

SHA 加密工具

html转js在线工具
html转js在线工具

html转js在线工具