4、ES9
1. rest 参数与 扩展运算符
ES6 中引入的 rest 参数与 spread 扩展运算符只针对于数组
ES9 为对象提供了同样功能的 rest 参数与 扩展运算符
function connect({host, username, ...user}) { // 除了host与username,其他参数都会存到user里面
console.log(host)
console.log(username)
console.log(user)
}
connect({
host: '192.168.0.0',
username: 'root',
password: 'root',
port: 8080
})
// 192.168.0.0
// root
// {password: "root", port: 8080}
const host = {
host: '192.168.0.0'
}
const username = {
username: 'root'
}
const password = {
password: 'root'
}
const port = {
port: 8080
}
const haha = {...host, ...username, ...password, ...port}
console.log(haha); // {host: "192.168.0.0", username: "root", password: "root", port: 8080}
2. 正则扩展
命名捕获分组
let str = 'http://www.baidu.com>百度';
let reg = /(.*)>(.*)/;
let reg1 = /(?<url>.*)>(?<text>.*)/; // 命名捕获分组: ?<分组名>
console.log(reg.exec(str)); // ["http://www.baidu.com>百度", "http://www.baidu.com", "百度", index: 0, input: "http://www.baidu.com>百度", groups: undefined]
console.log(reg1.exec(str)); // ["http://www.baidu.com>百度", "http://www.baidu.com", "百度", index: 0, input: "http://www.baidu.com>百度", groups: {url: "http://www.baidu.com", text: "百度"}]
// 加了命名捕获分组的,groups里面会有分组名与对应的值
exec 检索字符串中指定的值。返回找到的值,并确定其位置。index返回的是第一个匹配字符的位置
反向断言
正向断言: ?=n 匹配任何其后紧接指定字符串 n 的字符串
反向断言: ?<=n 匹配任何前面紧接指定字符串 n 的字符串
let str = 'ab123c34555d';
let reg = /(?<=b)\d+/g;
let reg1 = /\d+(?=d)/g;
console.log(str.match(reg)); // ["123"]
console.log(str.match(reg1)); // ["34555"]
dotAll 模式
dot .元字符,匹配除了换行符以外的任意单个字符
dotAll 匹配任意单个字符
// 模式修正符s
let str = `
a: 1,
b: 2
`;
let reg = /.*/gs;
let reg1 = /.*/g;
console.log(str.match(reg)); // (2) ["↵ a: 1,↵ b: 2↵", ""]
console.log(str.match(reg1)); // (6) ["", " a: 1,", "", " b: 2", "", ""]