ES10
仍然只是一個草案。可是除了Object.fromEntries
大多數功能已經在Chrome
中實現,因此你爲何不盡早開始探索它呢?當全部瀏覽器開始支持它時,你已經得到了領先優點,這只是時間問題。對於有興趣探索ES10的人來講,這是一份非外星人指南。javascript
ES10在新語言功能方面沒有ES6那麼重要,但它確實添加了一些有趣的東西(其中一些在目前版本的瀏覽器中還不起做用:02/20/2019)java
ES6
中最受歡迎的功能莫過於箭頭函數了,那麼ES10
中呢?node
BigInt
是第7種原始類型。正則表達式
BigInt
是一個任意精度的整數。這意味着變量如今能夠表明2^53個數字。並且最大限度是9007199254740992。算法
const b = 1n; //追加n來建立一個BigInt
數據庫
在過去的整數值大於9007199254740992不支持。若是超出,則該值將鎖定爲MAX_SAFE_INTEGER + 1
:express
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 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
中正式實現 - 若是沒有,它仍然值得一看。特別是若是你是一個正則表達式癮君子。api
若是你谷歌搜索"javascript string match all",第一條結果可能會是這樣的How do I write a regular expression to 「match all」? 。 排名靠前的結果會建議你使用String.match
匹配的時候在正則表達式或者RegExp.exc
或者RegExp.text
後加上/g
...數組
首先,咱們來看下舊的規範是如何運行的。瀏覽器
String.match
,match
只返回字符串參數第一個符合匹配的。
let string = 'Hello'
let matches = string.match('l')
console.log(matches[0]) // 'l'
複製代碼
匹配的結果是單個'l'
。(注意: match
匹配的結果存儲在matches[0]
而非在matches
),在字符串'hello'
中搜索匹配'l'
只有'l'
被返回來。使用regexp
參數也是獲得同樣的結果。
咱們把字符'l'
更換爲表達式/l/
:
let string = 'Hello'
let matches = string.match(/l/)
console.log(matches[0]) // 'l'
複製代碼
String.match
使用正則表達式帶上/g
標籤會返回多個匹配。
let string = 'Hello'
let ret = string.match(/l/g) // ['l', 'l']
複製代碼
Great...在低於ES10
的環境中咱們獲得了多個匹配結果,而且一直有效。
那麼爲何要用全新的matchAll
方法呢?在咱們更詳細地回答這個問題以前,讓咱們來看看capture group
。若是不出意外,你可能會學到新的有關正則表達式的東西。
在正則表達式中捕獲組只是在()
括號中提取匹配。你能夠從/regex/.exec(string)
和string.match
捕獲組。
一般捕獲組是在匹配規則中被建立的。輸出對象上建立groups
屬性如: (?<name>)
。要建立一個新的組名,只需在括號內添加 (?<name>)
屬性,分組(模式)匹配將成爲附加到match
對象的groups.name
。
看一個實際的例子:
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
時,會顯示下一個結果(它不會當即返回全部匹配項)。
控制檯輸出:
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()
/g
標誌的正則表達式...當從數據庫或外部源檢索未知的正則表達式並與古老的RegEx對象一塊兒使用時很是有用。RegExp
對象建立的正則表達式不能使用點(.
)運算符連接。RegEx
**對象跟蹤最後匹配位置的內部.lastIndex
屬性,這可能對複雜案例有破壞性的事情。.matchAll()
如何工做這是一簡單個例子。
咱們嘗試匹配字符串Hello
的全部e
和l
。由於返回了iterator,因此咱們用for ... of
處理它。
// Match all occurrences of the letters: 'e' 或者 '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()
具備上面列舉的全部好處,它是一個迭代器,因此咱們能夠用它來循環,這就是整個句法差別。
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
複製代碼
也許在美學上它與循環實現時的原始regex.exec
很是類似。但如前所述,因爲上述許多緣由,這是更好的方法。而且刪除/ g
不會致使無限循環。
如今能夠將導入分配給一個變量:
element.addEventListener('click', async () => {
const module = await import('./api-scripts/button-click.js')
module.clickEvent()
})
複製代碼
扁平化多維數組:
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]
複製代碼
let array = [1, 2, 3, 4, 5]
array.map(x => [x, x * 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]
複製代碼
再次扁平化數組:
array.flatMap(v => [v, v * 2])
[1, 2, 2, 4, 3, 6, 4, 8, 5, 10]
複製代碼
將鍵值對列表轉換爲對象。
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 }
複製代碼
let greeting = " Space around ";
greeting.trimEnd(); // " Space around";
greeting.trimStart(); // "Space around ";
複製代碼
此更新修復了字符U + D800
到U + DFFF
的處理,有時能夠進入JSON
字符串。這多是一個問題,由於JSON.stringify
可能會返回格式化爲沒有等效UTF-8
字符的值的這些數字。但JSON
格式須要UTF-8
編碼。
JSON
對象可用於解析JSON
格式(但也更多。)JavaScript JSON
對象也具備stringify
和parse
方法。
該解析方法適用於一個結構良好的JSON
字符串,如:
'{ 「prop1」 : 1, "prop2" : 2 }'; // A well-formed JSON format string
請注意,建立具備正確JSON
格式的字符串絕對須要使用圍繞屬性名稱的雙引號。缺乏...
或任何其餘類型的引號將不會產生格式良好的JSON
。
'{ 「prop1」 : 1, "meth" : () => {}}'; // Not JSON format string
JSON
字符串格式是不一樣的,從對象文本 ......它看起來幾乎相同,但可使用任何類型的周圍屬性名稱的報價,還能夠包括方法(JSON格式不容許的方法):
let object_literal = { property:1,meth:()=> {} };
不管如何,一切彷佛都很好。第一個示例看起來合規。但它們也是簡單的例子,大部分時間均可以毫無障礙地工做!
這是捕獲。ES10
以前的EcmaScript
實際上並不徹底支持JSON
格式。在ES10
以前的時代,不接受未轉義的行分隔符U + 2028
和段落分隔符U + 2029
字符:
若是這些字符悄悄進入你的JSON格式的字符串(好比說來自數據庫記錄),你最終可能花費數小時試圖弄清楚爲何程序的其他部分會產生解析錯誤。
因此,若是你傳遞的eval
一個字符串,像「console.log(‘hello’)
」這將執行JavaScript
語句(試圖經過字符串實際代碼轉換。)這也相似於如何JSON.parse
將處理您的JSON
字符串。
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, }
];
// Create our own sort criteria function:
let my_sort = (a, b) => a.count - b.count;
// Perform stable ES10 sort:
let sorted = fruit.sort(my_sort);
console.log(sorted);
複製代碼
控制檯輸出(項目以相反的順序出現):
Funcitons是對象,每一個對象都有個.toString()
方法由於它最初存在於Object.prototype.toString()
。全部的objects
(包括functions)都繼承至基於原型的類繼承。這意味着咱們已經有了function.toString()
方法了。
可是ES10進一步嘗試標準化全部對象和內置函數的字符串表示。如下新案例:
function () { console.log('Hello there.'); }.toString();
複製代碼
控制檯輸出(字符串格式的函數體:)
⇨ function () { console.log('Hello there.'); }
複製代碼
如下是其它案例:
Number.parseInt.toString();
⇨ function parseInt() { [native code] }
複製代碼
function () { }.bind(0).toString();
⇨ function () { [native code] }
複製代碼
Symbol.toString();
⇨ function Symbol() { [native code] }
複製代碼
Function().toString();
⇨ function anonymous() {}
複製代碼
function* () { }.toString();
⇨ function* () { }
複製代碼
Function.prototype.toString.call({});
⇨ Function.prototype.toString requires that 'this' be a Function" 複製代碼
在過去,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
}
複製代碼
但在某些狀況下,所需的error
變量未被使用:
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
子句。可是......事實並不是如此(正如 Douglas Massolari.所說)。
(() => {
try {
JSON.parse(text)
return true
} catch(err) {
return false
}
})()
=> false
複製代碼
你如今能夠跳過error
變量:
try {
JSON.parse(text);
return true;
}
catch
{
return false;
}
複製代碼
ES10以前全局this
沒有標準化。
生產代碼中,你必須手動添加以下代碼來標準化多個平臺的全局對象。
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
對象,從如今開始應該在任何平臺上訪問全局做用域:
// Access global array constructor
globalThis.Array(0, 1, 2);
⇨ [0, 1, 2]
// Similar to window.v = { flag: true } in <= ES5
globalThis.v = { flag: true };
console.log(globalThis.v);
⇨ { flag: true }
複製代碼
description
是一個只讀屬性,返回Symbol
對象的可選描述。
let mySymbol = 'My Symbol';
let symObj = Symbol(mySymbol);
symObj; // Symbol(My Symbol)
String(symObj) === `Symbol(${mySymbol})`); // true
symObj.description; // "My Symbol"
複製代碼
shebang unix
用戶會熟悉AKA
。
它指定一個解釋器(什麼將執行您的JavaScript文件?)
ES10標準化了這一點。我不會詳細介紹這個,由於這在技術上並非一個真正的語言功能。但它基本上統一了JavaScript在服務器端的執行方式。
$ ./index.js
複製代碼
代替:
$ node index.js
複製代碼
在類Unix操做系統下。
新的語法字符#(hash tag)如今直接在類主體做用域以及constructor
和類方法裏被用來定義variables
, functions
,getters
和setters
這是一個至關無心義的示例,僅關注新語法:
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 */
}
}
複製代碼
說實話,我認爲它使語言更難閱讀。
它仍然是我最喜歡的新功能,由於我喜歡C ++
時代的classes
。
ES10是一套還沒有有機會在生產環境中進行全面探索的新功能。若是您有任何更正,建議或任何其餘反饋,請告訴咱們。
我常常寫一個教程,由於我想本身學習一些科目。這是其中一次,有其餘人已經編譯的資源的幫助: