ES10特性詳解

摘要: 最新的JS特性。javascript

Fundebug經受權轉載,版權歸原做者全部。前端

ES10 還只是一個草案。可是除了 Object.fromEntries 以外,Chrome 的大多數功能都已經實現了,爲何不早點開始探索呢?當全部瀏覽器都開始支持它時,你將走在前面,這只是時間問題。java

在新的語言特性方面,ES10 不如 ES6 重要,但它確實添加了一些有趣的特性(其中一些功能目前還沒法在瀏覽器中工做: 2019/02/21)node

在 ES6 中,箭頭函數無疑是最受歡迎的新特性,在 ES10 中會是什麼呢?正則表達式

  • String .matchAll()
  • Dynamic import()
  • Array .flat() .flatMap()
  • Object .fromEntries()
  • String .trimStart() .trimEnd()
  • well-formed JSON.stringify()
  • stable Array .sort()
  • new Function .toString()
  • Standardized globalThis object

BigInt:任意精度整數

BigInt 是第七種 原始類型。算法

BigInt 是一個任意精度的整數。這意味着變量如今能夠 表示²⁵³ 數字,而不只僅是9007199254740992數據庫

const b = 1n;  // 追加 n 以建立 BigInt

在過去,不支持大於 9007199254740992 的整數值。若是超過,該值將鎖定爲 MAX_SAFE_INTEGER + 1:小程序

const limit = Number.MAX_SAFE_INTEGER;
⇨ 9007199254740991
limit + 1;
⇨ 9007199254740992
limit + 2;
⇨ 9007199254740992 <--- MAX_SAFE_INTEGER + 1 exceeded
const larger = 9007199254740991n;
⇨ 9007199254740991n
const integer = BigInt(9007199254740991); // initialize with number
⇨ 9007199254740991n
const same = BigInt("9007199254740991"); // initialize with "string"
⇨ 9007199254740991n

typeof

typeof 10;
⇨ 'number'
typeof 10n;
⇨ 'bigint'

等於運算符可用於兩種類型之間比較

10n === BigInt(10);
⇨ true
10n == 10;
⇨ true

數學運算符只能在本身的類型中工做

200n / 10n
⇨ 20n
200n / 20
⇨ Uncaught TypeError:
   Cannot mix BigInt and other types, use explicit conversions <

-運算符能夠操做, + 不可用

-100n
⇨ -100n
+100n
⇨ Uncaught TypeError:
  Cannot convert a BigInt value to a number

當你讀到這篇文章的時候,matchAll 可能已經在 Chrome C73 中正式實現了——若是不是,它仍然值得一看。特別是若是你是一個正則表達式(regex)愛好者。segmentfault

string.prototype.matchAll()

若是您運行谷歌搜索JavaScript string match all,第一個結果將是這樣的:如何編寫正則表達式「match all」?微信小程序

最佳結果將建議 String.match 與正則表達式和 /g 一塊兒使用或者帶有 /gRegExp.exec 或者帶有 /gRegExp.test

首先,讓咱們看看舊規範是如何工做的。

帶字符串參數的 String.match 僅返回第一個匹配:

let string = 'Hello';
let matches = string.match('l');
console.log(matches[0]); // "l"

結果是單個 "l"(注意:匹配存儲在 matches[0] 中而不是 matches)

「hello」中搜索 "l" 只返回 "l"

string.matchregex 參數一塊兒使用也是如此:

讓咱們使用正則表達式 /l/ 找到字符 串「hello」 中的 「l」 字符:

let string = "Hello";
let matches = string.match(/l/);
console.log(matches[0]); // "l"

添加 /g 混合

let string = "Hello";
let ret = string.match(/l/g); // (2) [「l」, 「l」];

很好,咱們使用 < ES10 方式獲得了多個匹配,它一直起做用。

那麼爲何要使用全新的 matchAll 方法呢? 在咱們更詳細地回答這個問題以前,讓咱們先來看看 捕獲組。若是不出意外,你可能會學到一些關於正則表達式的新知識。

正則表達式捕獲組

在 regex 中捕獲組只是從 () 括號中提取一個模式,可使用 /regex/.exec(string)string.match 捕捉組。

常規捕獲組是經過將模式包裝在 (pattern) 中建立的,可是要在結果對象上建立 groups 屬性,它是: (?<name>pattern)

要建立一個新的組名,只需在括號內附加 ?<name>,結果中,分組 (pattern) 匹配將成爲 group.name,並附加到 match對象,如下是一個實例:

字符串標本匹配:

這裏建立了 match.groups.color 和 match.groups.bird

const string = 'black*raven lime*parrot white*seagull';
const regex = /(?<color>.*?)\*(?<bird>[a-z0-9]+)/g;
while (match = regex.exec(string))
{
    let value = match[0];
    let index = match.index;
    let input = match.input;
    console.log(`${value} at ${index} with '${input}'`);
console.log(match.groups.color);
    console.log(match.groups.bird);
}

須要屢次調用 regex.exec 方法來遍歷整個搜索結果集。 在每次迭代期間調用**.exec** 時,將顯示下一個結果(它不會當即返回全部匹配項。),所以使用 while 循環。

輸出以下:

black*raven at 0 with 'black*raven lime*parrot white*seagull'
black
raven
lime*parrot at 11 with 'black*raven lime*parrot white*seagull'
lime
parrot
white*seagull at 23 with 'black*raven lime*parrot white*seagull'
white
seagull

但奇怪的是:

若是你從這個正則表達式中刪除 /g,你將永遠在第一個結果上建立一個無限循環。這在過去是一個巨大的痛苦。想象一下,從某個數據庫接收正則表達式時,你不肯定它的末尾是否有 /g,你得先檢查一下。

使用 .matchAll() 的好理由

  1. 在與捕獲組一塊兒使用時,它能夠更加優雅,捕獲組只是使用 () 提取模式的正則表達式的一部分。
  2. 返回一個迭代器而不是一個數組,迭代器自己是有用的。
  3. 迭代器可使用擴展運算符 (…) 轉換爲數組。
  4. 它避免了帶有 /g 標誌的正則表達式,當從數據庫或外部源檢索未知正則表達式並與陳舊的RegEx 對象一塊兒使用時,它很是有用。
  5. 使用 RegEx 對象建立的正則表達式不能使用點 (.) 操做符連接。
  6. 高級: RegEx 對象更改跟蹤最後匹配位置的內部 .lastindex 屬性,這在複雜的狀況下會形成嚴重破壞。

.matchAll() 是如何工做的?

讓咱們嘗試匹配單詞 hello 中字母 el 的全部實例, 由於返回了迭代器,因此可使用 for…of 循環遍歷它:

// Match all occurrences of the letters: "e" or "l" 
let iterator = "hello".matchAll(/[el]/);
for (const match of iterator)
    console.log(match);

這一次你能夠跳過 /g.matchall 方法不須要它,結果以下:

[ 'e', index: 1, input: 'hello' ] // Iteration 1
[ 'l', index: 2, input: 'hello' ] // Iteration 2
[ 'l', index: 3, input: 'hello' ] // Iteration 3

使用 .matchAll() 捕獲組示例:

.matchAll 具備上面列出的全部好處。它是一個迭代器,能夠用 for…of 循環遍歷它,這就是整個語法的不一樣。

const string = 'black*raven lime*parrot white*seagull';
const regex = /(?<color>.*?)\*(?<bird>[a-z0-9]+)/;
for (const match of string.matchAll(regex)) {
    let value = match[0];
    let index = match.index;
    let input = match.input;
    console.log(`${value} at ${index} with '${input}'`);
console.log(match.groups.color);
    console.log(match.groups.bird);
}

請注意已經沒有 /g 標誌,由於 .matchAll() 已經包含了它,打印以下:

black*raven at 0 with 'black*raven lime*parrot white*seagull'
black
raven
lime*parrot at 11 with 'black*raven lime*parrot white*seagull'
lime
parrot
white*seagull at 23 with 'black*raven lime*parrot white*seagull'
white
seagull

也許在美學上它與原始正則表達式很是類似,執行while循環實現。可是如前所述,因爲上面提到的許多緣由,這是更好的方法,移除 /g 不會致使無限循環。

動態導入

如今能夠將導入分配給變量:

element.addEventListener('click', async() => {
  const module = await import(`./api-scripts/button-click.js`);
  module.clickEvent();
})

Array.flat()

扁平化多維數組:

let multi = [1,2,3,[4,5,6,[7,8,9,[10,11,12]]]];
multi.flat();               // [1,2,3,4,5,6,Array(4)]
multi.flat().flat();        // [1,2,3,4,5,6,7,8,9,Array(3)]
multi.flat().flat().flat(); // [1,2,3,4,5,6,7,8,9,10,11,12]
multi.flat(Infinity);       // [1,2,3,4,5,6,7,8,9,10,11,12]

Array.flatMap()

let array = [1, 2, 3, 4, 5];
array.map(x => [x, x * 2]);


let array = [1, 2, 3, 4, 5];
array.map(x => [x, x * 2]);

結果:

[Array(2), Array(2), Array(2), Array(2), Array(2)]
0: (2) [1, 2]
1: (2) [2, 4]
2: (2) [3, 6]
3: (2) [4, 8]
4: (2) [5, 10]

使用 flatMap 方法:

array.flatMap(v => [v, v * 2]);
[1, 2, 2, 4, 3, 6, 4, 8, 5, 10]

Object.fromEntries()

將鍵值對列表轉換爲對象:

let obj = { apple : 10, orange : 20, banana : 30 };
let entries = Object.entries(obj);
entries;
(3) [Array(2), Array(2), Array(2)]
 0: (2) ["apple", 10]
 1: (2) ["orange", 20]
 2: (2) ["banana", 30]
let fromEntries = Object.fromEntries(entries);
{ apple: 10, orange: 20, banana: 30 }

String.trimStart() 與 String.trimEnd()

let greeting = "     Space around     ";
greeting.trimEnd();   // "     Space around";
greeting.trimStart(); // "Space around     ";

格式良好的 JSON.stringify()

此更新修復了字符 U+D800U+DFFF 的處理,有時能夠進入 JSON 字符串。 這多是一個問題,由於 JSON.stringify可能會將這些數字格式化爲沒有等效 UTF-8 字符的值, 但 JSON 格式須要 UTF-8 編碼。

解析方法使用格式良好的JSON字符串,如:

'{ 「prop1」 : 1, "prop2" : 2 }'; // A well-formed JSON format string

注意,要建立正確 JSON 格式的字符串,絕對須要在屬性名周圍加上雙引號。缺乏或任何其餘類型的引號都不會生成格式良好的JSON。

'{ 「prop1」 : 1, "meth" : () => {}}'; // Not JSON format string

JSON 字符串格式與 Object Literal 不一樣,後者看起來幾乎同樣,但可使用任何類型的引號括住屬性名,也能夠包含方法(JSON格式不容許使用方法):

let object_literal = { property: 1, meth: () => {} };

無論怎樣,一切彷佛都很好。第一個示例看起來是兼容的。但它們也是簡單的例子,大多數狀況下都能順利地工做!

U+2028 和 U+2029 字符

問題是, ES10 以前的 EcmaScript 實際上並不徹底支持 JSON 格式。前 ES10 時代不接受未轉義行分隔符 U+2028 和段落分隔符 U+2029 字符:

對於 U+D800 - U+DFFF 之間的全部字符也是如此

若是這些字符潛入 JSON 格式的字符串(假設來自數據庫記錄),你可能會花費數小時試圖弄清楚爲何程序的其他部分會產生解析錯誤。

所以,若是你傳遞 eval 這樣的字符串 「console.log(' hello ')」,它將執行 JavaScript語句 (經過嘗試將字符串轉換爲實際代碼),也相似於 JSON.parse 將處理你的 JSON 字符串的方式。

穩定的 Array.prototype.sort()

V8 以前的實現對包含10個以上項的數組使用了一種不穩定的快速排序算法。

一個穩定的排序算法是當兩個鍵值相等的對象在排序後的輸出中出現的順序與在未排序的輸入中出現的順序相同時。

但狀況再也不是這樣了,ES10 提供了一個穩定的數組排序:

var fruit = [
    { name: "Apple",      count: 13, },
    { name: "Pear",       count: 12, },
    { name: "Banana",     count: 12, },
    { name: "Strawberry", count: 11, },
    { name: "Cherry",     count: 11, },
    { name: "Blackberry", count: 10, },
    { name: "Pineapple",  count: 10, }
];
// 建立排序函數:
let my_sort = (a, b) => a.count - b.count;
// 執行穩定的ES10排序:
let sorted = fruit.sort(my_sort);
console.log(sorted);

控制檯輸出(項目以相反的順序出現):

代碼部署後可能存在的BUG無法實時知道,過後爲了解決這些BUG,花了大量的時間進行log 調試,這邊順便給你們推薦一個好用的BUG監控工具 Fundebug

新的Function.toString()

函數是對象,而且每一個對象都有一個 .toString() 方法,由於它最初存在於Object.prototype.toString() 上。 全部對象(包括函數)都是經過基於原型的類繼承從它繼承的。

這意味着咱們之前已經有 funcion.toString() 方法了。

可是 ES10 進一步嘗試標準化全部對象和內置函數的字符串表示。 如下是各類新案例:

典型的例子

function () { console.log('Hello there.'); }.toString();

控制檯輸出(函數體的字符串格式:)

⇨ function () { console.log('Hello there.'); }

下面是剩下的例子:

直接在方法名 .toString()

Number.parseInt.toString();
⇨ function parseInt() { [native code] }

綁定上下文

function () { }.bind(0).toString();
⇨ function () { [native code] }

內置可調用函數對象

Symbol.toString();
⇨ function Symbol() { [native code] }

動態生成的函數

function* () { }.toString();
⇨ function* () { }

prototype.toString

Function.prototype.toString.call({});
⇨ Function.prototype.toString requires that 'this' be a Function"

可選的 Catch Binding

在過去,try/catch 語句中的 catch 語句須要一個變量。 try/catch 語句幫助捕獲終端級別的錯誤:

try {
    // Call a non-existing function undefined_Function
    undefined_Function("I'm trying");
}
catch(error) {
    // Display the error if statements inside try above fail
    console.log( error ); // undefined_Function is undefined
}

在某些狀況下,所需的錯誤變量是未使用的:

try {
    JSON.parse(text); // <--- this will fail with "text not defined"
    return true; <--- exit without error even if there is one
}
catch (redundant_sometmes) <--- this makes error variable redundant
{
    return false;
}

編寫此代碼的人經過嘗試強制 true 退出 try 子句。可是,這並非實際發生的狀況

(() => {
    try {
        JSON.parse(text)
        return true
    } catch(err) {
        return false
    }
})()
=> false

在 ES10 中,捕獲錯誤的變量是可選的

如今能夠跳過錯誤變量:

try {
    JSON.parse(text);
    return true;
}
catch
{
    return false;
}

目前還沒法測試上一個示例中的 try 語句的結果,但一旦它出來,我將更新這部分。

標準化 globalThis 對象

這在ES10以前, globalThis 尚未標準化。

在產品代碼中,你能夠本身編寫這個怪物,在多個平臺上「標準化」它:

var getGlobal = function () {
    if (typeof self !== 'undefined') { return self; }
    if (typeof window !== 'undefined') { return window; }
    if (typeof global !== 'undefined') { return global; }
    throw new Error('unable to locate global object');
};

但即便這樣也不老是奏效。所以,ES10 添加了 globalThis 對象,從如今開始,該對象用於在任何平臺上訪問全局做用域:

// 訪問全局數組構造函數
globalThis.Array(0, 1, 2);
⇨ [0, 1, 2]

// 相似於 ES5 以前的 window.v = { flag: true }
globalThis.v = { flag: true };

console.log(globalThis.v);
⇨ { flag: true }

Symbol.description

description 是一個只讀屬性,它返回 Symbol 對象的可選描述。

let mySymbol = 'My Symbol';
let symObj = Symbol(mySymbol);
symObj; // Symbol(My Symbol)
symObj.description; // "My Symbol"

Hashbang 語法

也就是 unix 用戶熟悉的 shebang。它指定一個解釋器(什麼將執行JavaScript文件?)。

ES10標準化,我不會對此進行詳細介紹,由於從技術上講,這並非一個真正的語言特性,但它基本上統一了 JavaScript 在服務器端的執行方式。

$ ./index.js

代替

$ node index.js

ES10類: private、static 和 公共成員

新的語法字符 #octothorpe(hash tag)如今用於直接在類主體的範圍內定義變量,函數,getter 和 setter ......以及構造函數和類方法。

下面是一個毫無心義的例子,它只關注新語法:

class Raven extends Bird {
#state = { eggs: 10};
// getter
    get #eggs() { 
        return state.eggs;
    }
// setter
    set #eggs(value) {
        this.#state.eggs = value;
    }
#lay() {
        this.#eggs++;
    }
constructor() {
        super();
        this.#lay.bind(this);
    }
#render() {
        /* paint UI */
    }
}

老實說,我認爲這會讓語言更難讀。

原文:The Complete Guide to ES10 Features

關於Fundebug

Fundebug專一於JavaScript、微信小程序、微信小遊戲、支付寶小程序、React Native、Node.js和Java線上應用實時BUG監控。 自從2016年雙十一正式上線,Fundebug累計處理了10億+錯誤事件,付費客戶有Google、360、金山軟件、百姓網等衆多品牌企業。歡迎你們免費試用

相關文章
相關標籤/搜索