溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

ES10 特性的完整指南小結(jié)

發(fā)布時(shí)間:2020-10-11 18:04:15 來(lái)源:腳本之家 閱讀:137 作者:前端小智 欄目:web開發(fā)

本篇文章主要介紹了ES10 特性的完整指南,分享給大家,具體如下:

ES10 特性的完整指南小結(jié)

ES10 還只是一個(gè)草案。但是除了 Object.fromEntries 之外,Chrome 的大多數(shù)功能都已經(jīng)實(shí)現(xiàn)了,為什么不早點(diǎn)開始探索呢?當(dāng)所有瀏覽器都開始支持它時(shí),你將走在前面,這只是時(shí)間問(wèn)題。

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

在 ES6 中,箭頭函數(shù)無(wú)疑是最受歡迎的新特性,在 ES10 中會(huì)是什么呢?

ES10 特性的完整指南小結(jié)

BigInt -任意精度整數(shù)

BigInt 是第七種 原始類型。

BigInt 是一個(gè)任意精度的整數(shù)。這意味著變量現(xiàn)在可以 表示²⁵³ 數(shù)字,而不僅僅是9007199254740992

const b = 1n; // 追加 n 以創(chuàng)建 BigInt

在過(guò)去,不支持大于 9007199254740992 的整數(shù)值。如果超過(guò),該值將鎖定為 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'

等于運(yùn)算符可用于兩種類型之間比較:

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

數(shù)學(xué)運(yùn)算符只能在自己的類型中工作:

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

-運(yùn)算符可以操作, + 不可用

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

當(dāng)你讀到這篇文章的時(shí)候,matchAll 可能已經(jīng)在 Chrome C73 中正式實(shí)現(xiàn)了——如果不是,它仍然值得一看。特別是如果你是一個(gè)正則表達(dá)式(regex)愛(ài)好者。

string.prototype.matchAll()

如果您運(yùn)行谷歌搜索JavaScript string match all,第一個(gè)結(jié)果將是這樣的:如何編寫正則表達(dá)式“match all”?

最佳結(jié)果將建議 String.match 與正則表達(dá)式和 /g 一起使用或者帶有 /g 的 RegExp.exec 或者帶有 /g 的 RegExp.test 。

首先,讓我們看看舊規(guī)范是如何工作的。

帶字符串參數(shù)的 String.match 僅返回第一個(gè)匹配:

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

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

“hello”中搜索 "l" 只返回 "l"。

將 string.match 與 regex 參數(shù)一起使用也是如此:

讓我們使用正則表達(dá)式 /l/ 找到字符 串“hello” 中的 “l(fā)” 字符:

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(fā)”, “l(fā)”];

很好,我們使用 < ES10 方式得到了多個(gè)匹配,它一直起作用。

那么為什么要使用全新的 matchAll 方法呢? 在我們更詳細(xì)地回答這個(gè)問(wèn)題之前,讓我們先來(lái)看看 捕獲組。如果不出意外,你可能會(huì)學(xué)到一些關(guān)于正則表達(dá)式的新知識(shí)。

正則表達(dá)式捕獲組

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

常規(guī)捕獲組是通過(guò)將模式包裝在 (pattern) 中創(chuàng)建的,但是要在結(jié)果對(duì)象上創(chuàng)建 groups 屬性,它是: (?<name>pattern)。

要?jiǎng)?chuàng)建一個(gè)新的組名,只需在括號(hào)內(nèi)附加 ?<name>,結(jié)果中,分組 (pattern) 匹配將成為 group.name,并附加到 match 對(duì)象,以下是一個(gè)實(shí)例:

字符串標(biāo)本匹配:

ES10 特性的完整指南小結(jié)

這里創(chuàng)建了 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);
}

需要多次調(diào)用 regex.exec 方法來(lái)遍歷整個(gè)搜索結(jié)果集。 在每次迭代期間調(diào)用.exec 時(shí),將顯示下一個(gè)結(jié)果(它不會(huì)立即返回所有匹配項(xiàng)。),因此使用 while 循環(huán)。

輸出如下:

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è)正則表達(dá)式中刪除 /g,你將永遠(yuǎn)在第一個(gè)結(jié)果上創(chuàng)建一個(gè)無(wú)限循環(huán)。這在過(guò)去是一個(gè)巨大的痛苦。想象一下,從某個(gè)數(shù)據(jù)庫(kù)接收正則表達(dá)式時(shí),你不確定它的末尾是否有 /g,你得先檢查一下。

使用 .matchAll() 的好理由

  • 在與捕獲組一起使用時(shí),它可以更加優(yōu)雅,捕獲組只是使用 () 提取模式的正則表達(dá)式的一部分。
  • 它返回一個(gè)迭代器而不是一個(gè)數(shù)組,迭代器本身是有用的。
  • 迭代器可以使用擴(kuò)展運(yùn)算符 (…) 轉(zhuǎn)換為數(shù)組。
  • 它避免了帶有 /g 標(biāo)志的正則表達(dá)式,當(dāng)從數(shù)據(jù)庫(kù)或外部源檢索未知正則表達(dá)式并與陳舊的RegEx 對(duì)象一起使用時(shí),它非常有用。
  • 使用 RegEx 對(duì)象創(chuàng)建的正則表達(dá)式不能使用點(diǎn) (.) 操作符鏈接。
  • 高級(jí): RegEx 對(duì)象更改跟蹤最后匹配位置的內(nèi)部 .lastindex 屬性,這在復(fù)雜的情況下會(huì)造成嚴(yán)重破壞。

.matchAll() 是如何工作的?

讓我們嘗試匹配單詞 hello 中字母 el 的所有實(shí)例, 因?yàn)榉祷亓说?,所以可以使?for…of 循環(huán)遍歷它:

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

這一次你可以跳過(guò) /g, .matchall 方法不需要它,結(jié)果如下:

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

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

.matchAll 具有上面列出的所有好處。它是一個(gè)迭代器,可以用 for…of 循環(huán)遍歷它,這就是整個(gè)語(yǔ)法的不同。

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);
}

請(qǐng)注意已經(jīng)沒(méi)有 /g 標(biāo)志,因?yàn)?.matchAll() 已經(jīng)包含了它,打印如下:

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

也許在美學(xué)上它與原始正則表達(dá)式非常相似,執(zhí)行while循環(huán)實(shí)現(xiàn)。但是如前所述,由于上面提到的許多原因,這是更好的方法,移除 /g 不會(huì)導(dǎo)致無(wú)限循環(huán)。

動(dòng)態(tài)導(dǎo)入

現(xiàn)在可以將導(dǎo)入分配給變量:

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

Array.flat()

扁平化多維數(shù)組:

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]);

結(jié)果:

[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()

將鍵值對(duì)列表轉(zhuǎn)換為對(duì)象:

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()

此更新修復(fù)了字符 U+D800 到 U+DFFF 的處理,有時(shí)可以進(jìn)入 JSON 字符串。 這可能是一個(gè)問(wèn)題,因?yàn)?JSON.stringify 可能會(huì)將這些數(shù)字格式化為沒(méi)有等效 UTF-8 字符的值, 但 JSON 格式需要 UTF-8 編碼。

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

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

注意,要?jiǎng)?chuàng)建正確 JSON 格式的字符串,絕對(duì)需要在屬性名周圍加上雙引號(hào)。缺少或任何其他類型的引號(hào)都不會(huì)生成格式良好的JSON。

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

JSON 字符串格式與 Object Literal 不同,后者看起來(lái)幾乎一樣,但可以使用任何類型的引號(hào)括住屬性名,也可以包含方法(JSON格式不允許使用方法):

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

不管怎樣,一切似乎都很好。第一個(gè)示例看起來(lái)是兼容的。但它們也是簡(jiǎn)單的例子,大多數(shù)情況下都能順利地工作!

U+2028 和 U+2029 字符

問(wèn)題是, ES10 之前的 EcmaScript 實(shí)際上并不完全支持 JSON 格式。前 ES10 時(shí)代不接受未轉(zhuǎn)義行分隔符 U+2028 和段落分隔符 U+2029 字符:

ES10 特性的完整指南小結(jié)

ES10 特性的完整指南小結(jié)

對(duì)于 U+D800 - U+DFFF 之間的所有字符也是如此

如果這些字符潛入 JSON 格式的字符串(假設(shè)來(lái)自數(shù)據(jù)庫(kù)記錄),你可能會(huì)花費(fèi)數(shù)小時(shí)試圖弄清楚為什么程序的其余部分會(huì)產(chǎn)生解析錯(cuò)誤。

因此,如果你傳遞 eval 這樣的字符串 “console.log(' hello ')”,它將執(zhí)行 JavaScript語(yǔ)句 (通過(guò)嘗試將字符串轉(zhuǎn)換為實(shí)際代碼),也類似于 JSON.parse 將處理你的 JSON 字符串的方式。

穩(wěn)定的 Array.prototype.sort()

V8 之前的實(shí)現(xiàn)對(duì)包含10個(gè)以上項(xiàng)的數(shù)組使用了一種不穩(wěn)定的快速排序算法。

一個(gè)穩(wěn)定的排序算法是當(dāng)兩個(gè)鍵值相等的對(duì)象在排序后的輸出中出現(xiàn)的順序與在未排序的輸入中出現(xiàn)的順序相同時(shí)。

但情況不再是這樣了,ES10 提供了一個(gè)穩(wěn)定的數(shù)組排序:

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, }
];
// 創(chuàng)建排序函數(shù):
let my_sort = (a, b) => a.count - b.count;
// 執(zhí)行穩(wěn)定的ES10排序:
let sorted = fruit.sort(my_sort);
console.log(sorted);

控制臺(tái)輸出(項(xiàng)目以相反的順序出現(xiàn)):

ES10 特性的完整指南小結(jié)

新的Function.toString()

函數(shù)是對(duì)象,并且每個(gè)對(duì)象都有一個(gè) .toString() 方法,因?yàn)樗畛醮嬖谟贠bject.prototype.toString() 上。 所有對(duì)象(包括函數(shù))都是通過(guò)基于原型的類繼承從它繼承的。

這意味著我們以前已經(jīng)有 funcion.toString() 方法了。

但是 ES10 進(jìn)一步嘗試標(biāo)準(zhǔn)化所有對(duì)象和內(nèi)置函數(shù)的字符串表示。 以下是各種新案例:

典型的例子:

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

控制臺(tái)輸出(函數(shù)體的字符串格式:)

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

下面是剩下的例子:

直接在方法名 .toString()

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

綁定上下文:

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

內(nèi)置可調(diào)用函數(shù)對(duì)象:

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

動(dòng)態(tài)生成的函數(shù):

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

prototype.toString

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

可選的 Catch Binding

在過(guò)去,try/catch 語(yǔ)句中的 catch 語(yǔ)句需要一個(gè)變量。 try/catch 語(yǔ)句幫助捕獲終端級(jí)別的錯(cuò)誤:

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
}

在某些情況下,所需的錯(cuò)誤變量是未使用的:

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;
}

編寫此代碼的人通過(guò)嘗試強(qiáng)制 true 退出 try 子句。但是,這并不是實(shí)際發(fā)生的情況

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

在 ES10 中,捕獲錯(cuò)誤的變量是可選的

現(xiàn)在可以跳過(guò)錯(cuò)誤變量:

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

目前還無(wú)法測(cè)試上一個(gè)示例中的 try 語(yǔ)句的結(jié)果,但一旦它出來(lái),我將更新這部分。

標(biāo)準(zhǔn)化 globalThis 對(duì)象

這在ES10之前, globalThis 還沒(méi)有標(biāo)準(zhǔn)化。

在產(chǎn)品代碼中,你可以自己編寫這個(gè)怪物,在多個(gè)平臺(tái)上“標(biāo)準(zhǔn)化”它:

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 對(duì)象,從現(xiàn)在開始,該對(duì)象用于在任何平臺(tái)上訪問(wèn)全局作用域:

// 訪問(wèn)全局?jǐn)?shù)組構(gòu)造函數(shù)
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 是一個(gè)只讀屬性,它返回 Symbol 對(duì)象的可選描述。

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

Hashbang 語(yǔ)法

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

ES10標(biāo)準(zhǔn)化,我不會(huì)對(duì)此進(jìn)行詳細(xì)介紹,因?yàn)閺募夹g(shù)上講,這并不是一個(gè)真正的語(yǔ)言特性,但它基本上統(tǒng)一了 JavaScript 在服務(wù)器端的執(zhí)行方式。

$ ./index.js

代替

$ node index.js

ES10類:private、static 和 公共成員

新的語(yǔ)法字符 #octothorpe(hash tag)現(xiàn)在用于直接在類主體的范圍內(nèi)定義變量,函數(shù),getter 和 setter ......以及構(gòu)造函數(shù)和類方法。

下面是一個(gè)毫無(wú)意義的例子,它只關(guān)注新語(yǔ)法:

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 */
 }
}

老實(shí)說(shuō),我認(rèn)為這會(huì)讓語(yǔ)言更難讀。

代碼部署后可能存在的BUG沒(méi)法實(shí)時(shí)知道,事后為了解決這些BUG,花了大量的時(shí)間進(jìn)行l(wèi)og 調(diào)試,這邊順便給大家推薦一個(gè)好用的BUG監(jiān)控工具 Fundebug。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI