你可能错过的现代 JavaScript 特性

ES2015

二进制和八进制

``````const binaryZero = 0b0;
const binaryOne  = 0b1;
const binary255  = 0b11111111;
const binaryLong = 0b111101011101101;``````

``````// Pizza toppings
const olives    = 0b0001;
const ham       = 0b0010;
const pineapple = 0b0100;
const artechoke = 0b1000;

const pizza_ham_pineapple = pineapple | ham;
const pizza_four_seasons  = olives | ham | artechoke;``````

Number.isNaN()

``````isNaN(NaN)              === true
isNaN(null)             === false
isNaN(undefined)        === true
isNaN({})               === true
isNaN('0/0')            === true
isNaN('hello')          === true``````

``````Number.isNaN(NaN)       === true
Number.isNaN(null)      === false
Number.isNaN(undefined) === false
Number.isNaN({})        === false
Number.isNaN('0/0')     === false
Number.isNaN('hello')   === false``````

ES2016

指数（幂）运算符

``````2**2 === 4
3**2 === 9
3**3 === 27``````

（这很奇怪，因为我确信 JavaScript 已经有了这个 —— 我可能一直在考虑 Python）

Array.prototype.includes()

``````[1, 2, 3].includes(2)    === true
[1, 2, 3].includes(true) === false``````

`includes`Same Value Zero Algorithm（几乎与严格等式 `===` 相同）进行检查，但它可以处理 `NaN` 值。像相等检查一样，它将通过引用而不是内容来比较对象：

``````const object1 = {};
const object2 = {};

const array = [object1, 78, NaN];

array.includes(object1) === true
array.includes(object2) === false
array.includes(NaN)     === true``````

`includes` 可以通过第二个参数 `fromIndex` 让你提供一个偏移量：

``````// positions   0  1  2  3  4
const array = [1, 1, 1, 2, 2];

array.includes(1, 2) === true
array.includes(1, 3) === false``````

ES2018

强大的正则表达式

ES2018引入了一整套正则表达式特性：

Lookbehind 匹配项（前向匹配）

``````const regex = /(?<=\\$)\d+/;
const text  = 'This cost \$400';
text.match(regex) === ['400']``````

``````Look ahead:  (?=abc)
Look behind: (?<=abc)

Look ahead negative:  (?!abc)
Look behind negative: (?<!abc)``````

你可以命名捕获组

``````const getNameParts  = /(\w+)\s+(\w+)/g;
const name          = "Weyland Smithers";
const subMatches    = getNameParts.exec(name);

subMatches[1]     === 'Weyland'
subMatches[2]     === 'Smithers'``````

``````const getNameParts  = /(?<first>\w+)\s(?<last>\w+)/g;
const name          = "Weyland Smithers";
const subMatches    = getNameParts.exec(name);

const {first, last} = subMatches.groups
first             === 'Weyland'
last              === 'Smithers'``````

ES2019

Array.prototype.flat() & flatMap()

``````const multiDimensional = [
[1, 2, 3],
[4, 5, 6],
[7,[8,9]]
];

multiDimensional.flat(2) === [1, 2, 3, 4, 5, 6, 7, 8, 9]``````

`flatMap` 本质上是一个 `map`，也是深度为 1 的 `flat`。当从映射函数返回一个数组，但你不希望结果为嵌套数据结构时，用它很方便：

``````const texts = ["Hello,", "today I", "will", "use FlatMap"];

// with a plain map
const mapped = texts.map(text => text.split(' '));
mapped === ['Hello', ['today', 'I'], 'will', ['use', 'FlatMap']];

// with flatmap
const flatMapped = texts.flatMap(text => text.split(' '));
flatMapped === ['Hello', 'today', 'I', 'will', 'use', 'FlatMap'];``````

未绑定的捕获

``````try {
// something throws
} catch {
// don't have to do catch(e)
}``````

字符串修剪方法

``````const padded         = '          Hello world   ';
padded.trimStart() === 'Hello world   ';
padded.trimEnd()   === '          Hello world';``````

43.2k 声望
6.2k 粉丝
0 条评论