JS与ES6的查漏补缺(下)

本文最后更新于:2023年11月2日 下午

上篇见: JS与ES6的查漏补缺(上)

这部分主要记录ES6部分的内容

1 | 解构赋值

对象的解构赋值变量名和属性名不一致的情况:

1
2
3
4
5
6
7
let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"

let obj = { first: 'hello', last: 'world' };
let { first: f, last: l } = obj;
f // 'hello'
l // 'world'

解构的默认值:

1
2
3
4
5
6
var {x, y = 5} = {x: 1};
x // 1
y // 5

var {x: y = 3} = {x: 5};
y // 5

2 | 字符串扩展

ES6新增了一些有用的字符串方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
let s = 'Hello world!';
s.startsWith('Hello') // true
s.endsWith('!') // true
s.includes('o') // true
'hello'.repeat(2) // "hellohello"
'x'.padStart(5, 'ab') // 'ababx', 第一个参数是总长度
'x'.padStart(4, 'ab') // 'abax'

'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'

const s = ' abc ';

s.trim() // "abc"
s.trimStart() // "abc "
s.trimEnd() // " abc"

// 用于替换g修饰符的replaceAll, 下面两个等效
'aabbcc'.replace(/b/g, '_')
'aabbcc'.replaceAll('b', '_')
// 'aa__cc'

const str = 'hello';
str.at(1) // "e"

3 | 正则表达式

u修饰符

点(.)字符在正则表达式中,含义是除了换行符以外的任意单个字符。对于码点大于0xFFFF的 Unicode 字符,点字符不能识别,必须加上u修饰符。

1
2
3
4
var s = '𠮷';

/^.$/.test(s) // false
/^.$/u.test(s) // true

上面代码表示,如果不添加u修饰符,正则表达式就会认为字符串为两个字符,从而匹配失败。

y修饰符

表示"黏连", g修饰符在多次匹配表示从子字符串任意位置都可以, 而y表示必须从第一个

d修饰符

可以匹配每个组的开始和结束位置 (左闭右开)

1
2
3
4
5
const text = 'zabbcdef';
const re = /ab+(cd)/d;
const result = re.exec(text);

result.indices // [ [ 1, 6 ], [ 4, 6 ] ]

JS与ES6的查漏补缺(下)
https://blog.roccoshi.top/posts/31906/
作者
Moreality
发布于
2022年8月19日
许可协议