JavaScript版本历史

JavaScript诞生于1995年,并在1997年成为ECMA标准。
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可以同时执行多个异步函数,执行快的函数返回值返回给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执行的快,则
// function 1

Promise.any则是会返回第一个成功执行的Promise回调。

3. WeakRefs

WeakRef直译为弱引用,核心目的是加强GC减少大量内存的开销。

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 数字分隔符

类似java,数字之间可以使用_来隔开特殊位

# 普通数字
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() 动态引入

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

3. BigInt

BigInt提供更大(2^53之外)的整数,只需要在原数字后面加一个n,如12n即被识别为BigInt数据类型。它是除了String、Number、Boolean、Null、Undefined、Symbol外新的基础数据类型。

# 构造方法
const huge = 900000000n
const huge = BigInt(9000000)
const huge = BigInt('9000000')

4. Promise.allSettled

Promise.allSettled()方法返回一个在所有给定的promise都已经fulfilled或rejected后的promise,并带有一个对象数组,每个对象表示对应的promise结果。
旧的写法:

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执行失败,则整体成为reject,如果要得到每个的结果,需要对每个Promise做catch处理;Promise.allSettled会直接返回每个Promise失败与否的执行结果。

5. globalThis

globalThis旨在通过定义标准的全局属性来整合越来越分散的访问全局对象的方式。

# 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') {
  // 此环境中没有 setTimeout 方法!
}

# new case
if (typeof globalThis.setTimeout !== 'function') {
  //  此环境中没有 setTimeout 方法!
}

6. for in mechanicsfor...in顺序优化

以前在不同的引擎下for in循环出来的内容顺序是可能不一样的,现在标准化了。

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

开发者引用其它模块时,可以通过import.meta来获取模块的元信息。
import.meta必须在模块(modules)文件中使用,并且import.meta中的对象是可以被添加编辑或删除的。
import.meta常见包含的属性有:
(1) import.meta.url
它返回的是当前模块的文件路径。

# 比如这里有一个模块文件
<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" }

# 也可以解析参数
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的参数可以省略

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

2. JSON superset JSON超集

之前JSON一直并不是ECMAScript的子集,简单地说就是 ECMAScript 不允许U+2028(行分隔符)和U+2029(段分隔符)单独出现在字符串字面量中,而 JSON 允许,于是如果是单独出现了这两个字符的 JSON,直接当作 ECMAScript 代码,就会报错。现在可以啦。

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会产生异常。
现在可以避免此问题了。

7. String.prototype.{trimStart, trimEnd}

左右去空格。

8. Array.prototype.{flat, 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]]

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

优化字符串模版。

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)

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容