JavaScript版本歷史

JavaScript誕生于1995年,并在1997年成為ECMA標(biāo)準。
ECMAScript是JavaScript的官方名稱。
參考資料:

2022(es13)

// todo

2021(es12)

1. String.prototype.replaceAll

舊的寫法

'x'.replace('', '_');
// → '_x'
'xxx'.replace(/(?:)/g, '_');
// → '_x_x_x_'

新的寫法

'xxx'.replaceAll('', '_');
// → '_x_x_x_'

2. Promise.any

Promise.any是對Promise.rase的一個補充。

Promise.rase可以同時執(zhí)行多個異步函數(shù),執(zhí)行快的函數(shù)返回值返回給Promise.rase。如:

function runAsync1() {
    var res = new Promise (function(resolve, reject) {
        setTimeout(function() {
            resolve("function 1")
        },3000)
    });
    return res;
}

Promise
    .race([runAsync1(),runAsync2(),runAsync3()])
    .then(function(result) {
        console.log(result)
    })

# 如果runAsync1執(zhí)行的快,則
// function 1

Promise.any則是會返回第一個成功執(zhí)行的Promise回調(diào)。

3. WeakRefs

WeakRef直譯為弱引用,核心目的是加強GC減少大量內(nèi)存的開銷。

MDN提議盡量不要使,文檔指出GC在一個JavaScript引擎中的行為有可能在另一個JavaScript引擎中的行為大相徑庭,或者甚至在同一類引擎,不同版本中GC的行為都有可能有較大的差距。詳見??

4. Logical Assignment Operators 擴充邏輯賦值

// "Or Or Equals" (or, the Mallet operator :wink:)
a ||= b;
a || (a = b);

// "And And Equals"
a &&= b;
a && (a = b);

// "QQ Equals"
a ??= b;
a ?? (a = b);

5. Numeric separators 數(shù)字分隔符

類似java,數(shù)字之間可以使用_來隔開特殊位

# 普通數(shù)字
1_000_000_000 
1_0000
0.000_001

# 二進制
0b1010_0001_1000_0101

# 16進制
0xA0_B0_C0

# BigInt
1_000_000_000_000n

# 8進制
0o1234_5670

2020(es11)

1. String.prototype.matchAll

// todo

2. import() 動態(tài)引入

import(`@/${modelpath}`).then(module => {}).catch(err => {})

3. BigInt

BigInt提供更大(2^53之外)的整數(shù),只需要在原數(shù)字后面加一個n,如12n即被識別為BigInt數(shù)據(jù)類型。它是除了String、Number、Boolean、Null、Undefined、Symbol外新的基礎(chǔ)數(shù)據(jù)類型。

# 構(gòu)造方法
const huge = 900000000n
const huge = BigInt(9000000)
const huge = BigInt('9000000')

4. Promise.allSettled

Promise.allSettled()方法返回一個在所有給定的promise都已經(jīng)fulfilled或rejected后的promise,并帶有一個對象數(shù)組,每個對象表示對應(yīng)的promise結(jié)果。
舊的寫法:

function reflect(promise) {
  return promise.then(
    (v) => {
      return { status: 'fulfilled', value: v };
    },
    (error) => {
      return { status: 'rejected', reason: error };
    }
  );
}

const promises = [ fetch('index.html'), fetch('https://does-not-exist/') ];
const results = await Promise.all(promises.map(reflect));
const successfulPromises = results.filter(p => p.status === 'fulfilled');

替換寫法

const promises = [ fetch('index.html'), fetch('https://does-not-exist/') ];
const results = await Promise.allSettled(promises);
const successfulPromises = results.filter(p => p.status === 'fulfilled');

Promise.all如果有一個Promise執(zhí)行失敗,則整體成為reject,如果要得到每個的結(jié)果,需要對每個Promise做catch處理;Promise.allSettled會直接返回每個Promise失敗與否的執(zhí)行結(jié)果。

5. globalThis

globalThis旨在通過定義標(biāo)準的全局屬性來整合越來越分散的訪問全局對象的方式。

# old case
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');
};

var globals = getGlobal();

if (typeof globals.setTimeout !== 'function') {
  // 此環(huán)境中沒有 setTimeout 方法!
}

# new case
if (typeof globalThis.setTimeout !== 'function') {
  //  此環(huán)境中沒有 setTimeout 方法!
}

6. for in mechanicsfor...in順序優(yōu)化

以前在不同的引擎下for in循環(huán)出來的內(nèi)容順序是可能不一樣的,現(xiàn)在標(biāo)準化了。

7. Optional Chaining 可選鏈式操作符

a?.b                        
// a == null ? undefined : a.b

a?.[x]                      
// a == null ? undefined : a[x]

a?.b()                      
// a == null ? undefined : a.b() 

a?.()                       
// a == null ? undefined : a()  

a?.b[3].c?.(x).d
// a == null ? undefined : a.b[3].c == null ? undefined : a.b[3].c(x).d

# 配合??使用
a?.b ?? 200

8. Nullish Coalescing Operator 空值合并操作符

# null, undefined, 0, ''取右
console.log(0 || 'h')
// 'h'

# 僅在null和undefined取右
console.log(0 ?? 'h')
// 0

9. import.meta

開發(fā)者引用其它模塊時,可以通過import.meta來獲取模塊的元信息。
import.meta必須在模塊(modules)文件中使用,并且import.meta中的對象是可以被添加編輯或刪除的。
import.meta常見包含的屬性有:
(1) import.meta.url
它返回的是當(dāng)前模塊的文件路徑。

# 比如這里有一個模塊文件
<script type="module" src="my-module.mjs"></script>
# 或者在腳本中引用
import './my-module.mjs'

# 可以通過`import.meta`獲取到本地模塊/外部腳本的地址
console.log(import.meta)
// { url: "file:///home/user/my-module.mjs" }

# 也可以解析參數(shù)
import './my-module.mjs?someURLInfo=5'
console.log(new URL(import.meta.url).searchParams.get('someURLInfo'))
// 5

# 獲取同級文件
await fetch(new URL("../hamsters.jpg", import.meta.url))

(2) import.meta. scriptElement
用于獲取引入的script文件的信息。

<script type="module" src="my-module.mjs" data-foo="abc"></script>

# my-module.mjs
console.log(import.meta.scriptElement.dataset.foo)
// "abc"

2019(es10)

1. Optional catch binding catch的參數(shù)可以省略

try {
  // ...
} catch {
  // ...
}

2. JSON superset JSON超集

之前JSON一直并不是ECMAScript的子集,簡單地說就是 ECMAScript 不允許U+2028(行分隔符)和U+2029(段分隔符)單獨出現(xiàn)在字符串字面量中,而 JSON 允許,于是如果是單獨出現(xiàn)了這兩個字符的 JSON,直接當(dāng)作 ECMAScript 代碼,就會報錯。現(xiàn)在可以啦。

3. Symbol.prototype.description

Symbol的description是一個只讀屬性,用于返回Symbol
對象的可選描述字符串。

console.log(Symbol('desc').description);
// expected output: "desc"

console.log(Symbol.iterator.description);
// expected output: "Symbol.iterator"

console.log(Symbol.for('foo').description);
// expected output: "foo"

console.log(`${Symbol('foo').description}bar`);
// expected output: "foobar"

4. Function.prototype.toString

toString做了一些更新,詳情見MDN

5. Object.fromEntries

舊的寫法

[['foo', true], ['bar', false]].reduce((acc, [ key, val ]) => Object.assign(acc, { [key]: val }), {})

新的寫法

Object.fromEntries([['foo', true], ['bar', false]])

6. Well-formed JSON.stringify

舊的JSON.stringify默認以UTF-8編碼輸出,對于UTF-16會產(chǎn)生異常。
現(xiàn)在可以避免此問題了。

7. String.prototype.{trimStart, trimEnd}

左右去空格。

8. Array.prototype.{flat, flatMap}

# 扁平化數(shù)組
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]]

const arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 去除空值
const arr5 = [1, 2, , 4, 5];
arr5.flat();
// [1, 2, 4, 5]
[2, 3, 4].flatMap((x) => [x, x * 2]);
// [2, 4, 3, 6, 4, 8]

2018(es9)

1. Lifting template literal restriction

優(yōu)化字符串模版。

2. s(dotAll) flag for regular experssions

3. RegExp named capture groups

4. Rest/Spread Properties

let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
x; // 1
y; // 2
z; // { a: 3, b: 4 }

let n = { x, y, ...z };
n; // { x: 1, y: 2, a: 3, b: 4 }

5. RegExp Lookbehind Assertions

6. RegExp Unicode Property Escapes

7. Promise.prototype.finally

8. Asynchronous Iteration

2017(es8)

1. Object.values / Object.entries

2. String padding

3. Object.getOwnPropertyDescriptors

4. Trailing commas in function parameter lists and calls

5. Async functions

6. Shared memory and atomics

2016(es7)

1. Arrays.prototype.includes

2. Exponentiation operator

2015(es6)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容