1.ES6 (ES2015)?
1.1 Class?
JavaScript 是一種使用原型鏈的語(yǔ)言。 早期像面向?qū)ο筮@樣的概念都是通過(guò)原型鏈來(lái)做的,比較復(fù)雜,Class 終于在 ES6 中引入了。?
class Animal {?
constructor(name, color) {?
this.name = name;?
this.color = color;?
} // This is a property on the prototype chain?
toString() {?
console.log('name:' + this.name + ', color:' + this.color);?
} }
var animal = new Animal('myDog', 'yellow');
animal.toString();console.log(animal.hasOwnProperty('name')); //true
console.log(animal.hasOwnProperty('toString')); // false
console.log(animal.__proto__.hasOwnProperty('toString')); // true
class Cat extends Animal?
{ constructor(action)?
{ super('cat', 'white'); this.action = action; }?
toString() {?
console.log(super.toString());?
} }?
var cat = new Cat('catch');
cat.toString();
console.log(cat instanceof Cat); // true
console.log(cat instanceof Animal); // true?
1.2 module?
每個(gè)模塊都有自己的命名空間,避免沖突,使用 import 和 export 來(lái)導(dǎo)入導(dǎo)出,默認(rèn)將 .js 文件視為模塊。?
1.3 Arrow?
function 箭頭函數(shù) () => {…}是函數(shù)的縮寫,有了箭頭函數(shù)再也不用寫 var self = this, var that = this 等類代碼。
const add = (a, b) => { return a + b; };
const res = add(1, 2); // 3
const minus = (a, b) => a - b;
const res1 = minus(5, 1); // 4?
1.4 函數(shù)參數(shù)默認(rèn)值?
如果函數(shù)不傳參數(shù),則使用默認(rèn)值,更簡(jiǎn)潔。?
function example(height = 5, width = 6) {?
const newH = height * 2;?
const newW = width * 4;?
return newH + newW;?
}?
example(); // 34 (5*2 + 6*4)?
1.5 模板字符串?
以前,長(zhǎng)字符串的組合使用+號(hào)連接,可讀性差,使用模板字符串更容易閱讀。?
const firstName = 'water';
const lastName = 'fish';// not use template
literalconst name = 'Hello, My name is' + firstName + ', ' + lastName;
// use template literalconst
nameWithLiteralString = `Hello, My name is ${firstName}, ${lastName}`;?
1.6 解構(gòu)?
const arr = [1, 2, 3, 4, 5];
const [one, two, three] = arr;
console.log(one); // 1
console.log(two); // 2?
...
// To skip certain values
const [first,,,,last] = arr;
console.log(first); // 1
console.log(last); // 5?
// Objects can also be destructurized and assigned
const student = { name: 'waterfish', age: 28, };
const {name, age, city} = student;
console.log(name);// waterfish
console.log(age); // 28?
1.7 spread?
操作符 const arr1 = ['A', 'B'];?
const arr2 = ['0', ...arr1, '1', '2'];
conslog.log(arr2); // [0, A, B, 1, 2]?
用三個(gè)點(diǎn)…表示,Array 可以擴(kuò)展,而如果是 Object,則根據(jù) key-value 進(jìn)行擴(kuò)展。?
1.8 對(duì)象屬性縮寫?
因?yàn)闃?gòu)成 newCustomer 對(duì)象屬性的 name、age 的 key、value 相同,所以省略 value。?
const name = 'waterfish', age = 28;
// Before ES6, we must write like this
const customer = { name: name, age: age, }; // //
{name: 'waterfish', age: 28}?
// After ES6, we can do it
const newCustomer = { name, age, };?
// {name: 'waterfish', age: 28}?
1.9 Promise Promise?
是一種解決異步(非同步)寫法的方案,比原來(lái)的 callback 寫法更優(yōu)雅。使用 Promise 可以解決 hell callback。?
const waitSecond = new Promise((resolve, reject) => {
?setTimeout(resolve, 1000); });?
waitSecond .then(() => {?
console.log('hello after 1 second.');?
// output this line after 1 second?
return waitSecond; }) .then(() => {?
console.log('World after 2 sceond.');?
// output this line after 2second });?
1.10 let, const 替換 var?
let:通用變量,可以重寫。?
const:一旦聲明,其內(nèi)容不可修改。因?yàn)閿?shù)組和對(duì)象都是指針,所以可以在不改變指針的情況下增加或減少它們的內(nèi)容。
2.ES7 (ES2016)?
2.1 Array.prototype.includes()?
用于判斷數(shù)組中是否包含指定值,如果包含則返回 true,否則,返回 false。因?yàn)榉祷夭紶栔?,?indexOf 的語(yǔ)義化更加清晰。?
const arr = [1, 2, 3, 4, 5];?
arr.include(3); // true?
if (arr.include(3)) { ... }
// ... Equivalent to the previous writing of indexOf arr.indexOf(3);?
// 2 (return its array position)
// If you want to write it in the if, you must add `> -1`, which is not as clear as the include in ES7 in terms of semanticsif (arr.indexOf(3) > -1) { ... }?
2.2 指數(shù)運(yùn)算符?
console.log(2 ** 10); // 1024// equal to
console.log(Math.pow(2, 10)); // 1024?
3.ES8 (ES2017)?
發(fā)布了一個(gè)更完美的 async,await,直接讓異步的寫法看起來(lái)像同步的。?
3.1 async, await 異步函數(shù)是使用 async 關(guān)鍵字聲明的函數(shù),其中允許使用 await 關(guān)鍵字。 async 和 await 關(guān)鍵字使基于 Promise 的異步行為能夠以更簡(jiǎn)潔的方式編寫,避免顯式配置 Promise 鏈的需要。?
async test() {?
try {?
const result = await otherAsyncFunction();
console.log(result); // output?
result } catch(e) {?
console.log(e); // Can catch errors if otherAsyncFunction() throws an error } }?
3.2 Object.values()?
返回對(duì)象自身屬性的所有值,不包括繼承的值。?
const exampleObj = { a: 1, b: 2, c: 3, d: 4 };console.log(Object.value(exampleObj)); // [1, 2, 3, 4];// To do the same thing before, use the following notation. much verboseconst values = Object.keys(exampleObj).map((key) => exampleObj[key]);?
3.3 Object.entries()?
返回一個(gè)可枚舉的鍵,value 中存儲(chǔ)的是鍵的值。 const Obj = { a: 1, b: 2, c: 3, d: 4 };console.log(Object.entries(Obj)); // [[a, 1], [b, 2], [c, 3], [d, 4]]; // Usually used with forfor (const [key, value] of Object.entries(Obj)) { console.log(`key: ${key}, value: ${value}`);}// key: a, value: 1// key: b, value: 2// key: c, value: 3// key: d, value: 4?
3.4 padStart() & padEnd()?
您可以在字符串的開(kāi)頭或結(jié)尾添加額外的內(nèi)容,并將其填充到指定的長(zhǎng)度。過(guò)去,這些功能通常是通過(guò) lodash 等通用幫助工具包引入 的。 String.padStart(fillingLength, FillingContent);// If the content to be filled is too much and exceeds the fill length,// it will be filled from the leftmost to the upper limit of the length,// and the excess will be truncated 最常用的情況應(yīng)該是金額,填指定長(zhǎng)度,不足補(bǔ) 0。 // padStart'100'.padStart(5, 0); // 00100// If the content to be padded exceeds the padding length. Then fill in from the left to the upper limit of the length'100'.padStart(5, '987'); // 98100 // padEnd'100'.padEnd(5, 9); // 10099// If the content to be padded exceeds the padding length. Then fill in from the right to the upper limit of the length'100'.padEnd(5, '987'); // 10098?
3.5 trailing comma?
ECMAScript 2017 支持函數(shù)參數(shù)中的尾隨逗號(hào)。 function f(p) {}function f(p) {} (p) => {};(p) => {}; 3.6 Object.getOwnPropertyDescriptors() 獲取您自己的描述符,一般開(kāi)發(fā)業(yè)務(wù)需求通常不會(huì)使用這些描述符。 const exampleObj = { a: 1, b: 2, c: 3, d: 4 };Object.getOwnPropertyDescriptors(exampleObj);// {a: {…}, b: {…}, c: {…}, d: {…}}// a: {value: 1, writable: true, enumerable: true, configurable: true}// b: {value: 2, writable: true, enumerable: true, configurable: true}// c: {value: 3, writable: true, enumerable: true, configurable: true}// d: {value: 4, writable: true, enumerable: true, configurable: true}// __proto__: Object?
3.7 共享數(shù)組緩沖區(qū)(shared array buffer)
?SharedArrayBuffer 是原始二進(jìn)制數(shù)據(jù)的固定長(zhǎng)度緩沖區(qū),類似于 ArrayBuffer??捎糜谠诠蚕韮?nèi)存上創(chuàng)建數(shù)據(jù),與 ArrayBuffer 不同,SharedArrayBuffer 不能分離。?
3.8 Atomics object Atomics?
對(duì)象提供一組靜態(tài)方法來(lái)對(duì) SharedArrayBuffer 執(zhí)行原子操作。如果一個(gè)多線程同時(shí)在同一個(gè)位置讀寫數(shù)據(jù),原子操作保證了正在操作的數(shù)據(jù)符合預(yù)期:即在上一個(gè)子操作結(jié)束后執(zhí)行下一個(gè),操作不中斷。 可以說(shuō)是針對(duì) Node.Js 中多線程 Server 的開(kāi)發(fā)而加強(qiáng)的功能,在前端開(kāi)發(fā)中使用的機(jī)會(huì)相當(dāng)?shù)?,目?Chrome 已經(jīng)支持。?
4.ES9 (ES2018)?
4.1 await loop?
在異步函數(shù)中,有時(shí)需要在同步 for 循環(huán)中使用異步(非同步)函數(shù)。for 循環(huán)本身還是同步的,整個(gè) for 循環(huán)會(huì)在循環(huán)中的異步函數(shù)執(zhí)行完之前執(zhí)行完,然后里面的異步函數(shù)會(huì)一個(gè)一個(gè)執(zhí)行。ES9 加入了異步迭代器,允許 await 配合使用 for 循環(huán)逐步執(zhí)行異步操作。?
async function process(array) { for await (const i of array) { doSomething(i); } }?
4.2 promise.finally()?
無(wú)論是成功(.then())還是失?。?catch()),都會(huì)在 Promise 之后執(zhí)行的代碼。?
function process() { process1() .then(process2) .then(process3) .catch((err) => { console.log(err); }) .finally(() => { console.log(`it must execut no matter success or fail`); }); }?
4.3 Rest & Spread?
const myObject = { a: 1, b: 2, c: 3,};const { a, ...r } = myObject;// a = 1// r = { b: 2, c: 3 }// Can also be used in function input parametersfunction restObjectInParam({ a, ...r }) { console.log(a); // 1 console.log(r); // {b: 2, c: 3}}restObjectInParam({ a: 1, b: 2, c: 3,});?
5.ES10 (ES2019)?
5.1 Array.prototype.flat() & Array.prototype.flatMap()
?const arr1 = [1, 2, [3, 4]];arr1.flat(); // [1, 2, 3, 4] const arr2 = [1, 2, [3, 4, [5, 6]]];arr2.flat(); // [1, 2, 3, 4, [5, 6]]// Pass in a number in flat, representing the flattening deptharr2.flat(2); // [1, 2, 3, 4, 5, 6] 下面是 flatMap 方法: let arr = ['water', '', 'fish']; arr.map((s) => s.split(''));// [[w, a, t, e, r], [], [f, i, s, h] arr.flatMap((s) => s.split(''));// [w, a,t,e,r, , f, i, s, h]?
5.2 String.prototype.trimStart() & String.prototype.trimEnd()?
trimStart() 方法從字符串的開(kāi)頭刪除空格,trimLeft() 是該方法的別名。 const greeting = ' Hello world! '; console.log(greeting); // expected output: ?Hello world! ; console.log(greeting.trimStart()); // expected output: Hello world! ; trimEnd() 方法刪除字符串末尾的空格,trimRight() 是該方法的別名。 const greeting = ' ??Hello world! ??'; console.log(greeting); // expected output: ???Hello world! ??; console.log(greeting.trimEnd()); // expected output: ???Hello world!;?
5.3 Object.fromEntries()?
將鍵值對(duì)列表轉(zhuǎn)換為對(duì)象。 const entries = new Map([ ['foo', 'bar'], ['baz', 42], ]);const obj = Object.fromEntries(entries);console.log(obj);// expected output: Object { foo: bar, baz: 42 }?
5.4 String.prototype.matchAll matchAll()?
方法返回一個(gè)迭代器,遍歷將字符串與正則表達(dá)式匹配的所有結(jié)果,包括捕獲組。 const regexp = /t(e)(st(\d?))/g; const str = 'test1test2'; const array = [...str.matchAll(regexp)]; console.log(array[0]); // expected output: Array [test1, e, st1, 1] console.log(array[1]); // expected output: Array [test2, e, st2, 2]?
5.5 BigInt?
const theBiggestInt = 9007199254740991n;const alsoHuge = BigInt(9007199254740991);// ? 9007199254740991nconst hugeString = BigInt('9007199254740991');// ? 9007199254740991nconst hugeHex = BigInt('0x1fffffffffffff');// ? 9007199254740991nconst hugeBin = BigInt( '0b11111111111111111111111111111111111111111111111111111' );// ? 9007199254740991n?
6.ES11 (ES2020)?
6.1 Promise.allSettled() Promise.allSettled()?
方法返回一個(gè) Promise,當(dāng)所有給定的 Promise 都已完成或被拒絕時(shí),該 Promise 就會(huì)完成,其中每個(gè)對(duì)象都描述每個(gè) Promise 的結(jié)果。 當(dāng)您有多個(gè)不依賴于彼此成功完成的異步任務(wù)時(shí),或者當(dāng)您總是想知道每個(gè) Promise 的結(jié)果時(shí)通常會(huì)使用它。 相反,如果任務(wù)相互依賴、或者您希望其中任何一個(gè) Promise 失敗后則立即拒絕,則由 Promise.all() 返回的 Promise 可能更合適。?
const promise1 = Promise.resolve(3);const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo') );const promises = [promise1, promise2];Promise.allSettled(promises).then((results) => results.forEach((result) => console.log(result.status)) );// expected output:// fulfilled// rejected?
6.2 Optional ??
const username = user?.name || 'guest';?
6.3 Nullish?
coalescing operator ?? 在 JavaScript 中,0、null 或 undefined 會(huì)自動(dòng)轉(zhuǎn)為 false,但有時(shí)候希望將返回值設(shè)置為 0。 const username = user.level ?? 'no level';// output 0. if level is not available, it becomes 'no level'.?
6.4 Dynamic-import?
動(dòng)態(tài)引入 el.onclick = () => { import(`/js/logger.js`) .then((module) => { module.doSomthing(); }) .catch((err) => { handleError(err); }); };?
6.5 GlobalThis?
全局 globalThis 屬性包含全局 this 值,類似于全局對(duì)象。
?function canMakeHTTPRequest() { return typeof globalThis.XMLHttpRequest === 'function'; }console.log(canMakeHTTPRequest());// expected output (in a browser): true?
7.ES12 (ES2021)?
7.1 Promise.any()?
Promise.any() 接受一個(gè)可迭代的 Promise 對(duì)象,每當(dāng)可迭代對(duì)象中的任何一個(gè) Promise fullfill 時(shí)它都返回一個(gè) Promise,其中包含已 fullfill 的 Promise 的值。如果所有的 Promise reject 則返回 AggregateError 對(duì)象,其是 ERROR 對(duì)象的一個(gè)子類,默認(rèn)搜集所有 Error 并分組。?
const p1 = new Promise((resolve) => { setTimeout(() => { resolve('p1 resolved value'); }, 1000); });const p2 = new Promise((resolve) => { setTimeout(() => { resolve('p2 resolved value'); }, 500); });const p3 = new Promise((resolve) => { setTimeout(() => { resolve('p3 resolved value'); }, 1800); });Promise.any([p1, p2, p3]).then((value) => { console.log(value); }); // p2 resolved value?
7.2 邏輯賦值運(yùn)算符?
在開(kāi)發(fā)過(guò)程中,可以使用在 ES2020 引入的邏輯運(yùn)算符 ||、&& 和 ?? (Nullish coalescing operator)來(lái)解決一些問(wèn)題。而 ES2021 會(huì)提出 ||= , &&= , ??= ,概念類似于 += :?
let b = 2; b += 1;// equal to b = b + 1let a = null; a ||= 'some random text'; // a become to'some random text'// equal a = a || 'some random text'let c = 'some random texts'; c &&= null; // c become to null// equal to c = c && nulllet d = null; d ??= false; // d become to false// equal to d = d ?? false?
7.3 弱引用(WeakRef)?
WeakRef 對(duì)象持有對(duì)對(duì)象的弱引用,稱為其目標(biāo)或引用對(duì)象。對(duì)對(duì)象的弱引用是不會(huì)阻止對(duì)象被垃圾收集器回收的引用。 普通(或強(qiáng))引用將對(duì)象保存在內(nèi)存中,當(dāng)一個(gè)對(duì)象不再具有任何強(qiáng)引用時(shí),JavaScript 引擎的垃圾收集器可能會(huì)銷毀該對(duì)象并回收其內(nèi)存,如果發(fā)生這種情況,您將無(wú)法再?gòu)娜跻弥蝎@取對(duì)象。
8.ES13 (ES2022)?
期待不一樣的東西
原文鏈接:https://medium.com/