#ES7-10
一.ECMASript 7 新特性
1.1.Array.prototype.includes
Includes 方法用来检测数组中是否包含某个元素,返回布尔类型值
const teams = ['nets', 'rockets', 'suns'];
console.log(teams.includes('nets'));//true
console.log(teams.includes('lakers'));//false
1.2指数操作符
在 ES7 中引入指数运算符**,用来实现幂运算,功能与 Math.pow 结果相同
console.log(2**10);//1024
二.ECMASript 8 新特性
2.1async 函数
- async 函数的返回值为 promise 对象,
- promise 对象的结果由 async 函数执行的返回值决定
async function fn() {
return new Promise((resolve, reject) => {
resolve('成功的数据');
//reject("失败的错误");
});
}
const result = fn();
result.then(value => {
console.log(value);
}, reason => {
console.warn(reason);
})
2.2await表达式
- await 必须写在 async 函数中
- await 右侧的表达式一般为 promise 对象
- await 返回的是 promise 成功的值
- await 的 promise 失败了, 就会抛出异常, 需要通过 try…catch 捕获处理
const p = new Promise((resolve, reject) => {
reject("失败了");
})
async function main() {
try {
let result = await p;
console.log(result);
} catch (e) {
console.log(e)
}
}
main();
2.3Object.values 和 Object.entries
-
Object.values()方法返回一个给定对象的所有可枚举属性值的数组
-
Object.entries()方法返回一个给定对象自身可遍历属性 [key,value] x
的数组
2.3.Object.getOwnPropertyDescriptors
该方法返回指定对象所有自身属性的描述对象
三.ECMASript 9 新特性
3.1Rest/Spread 属性
Rest 参数与 spread 扩展运算符在 ES6 中已经引入,不过 ES6 中只针对于数组,
在 ES9 中为对象提供了像数组一样的 rest 参数和扩展运算符
function connect({host, port, ...user}) {
console.log(host);
console.log(port);
console.log(user);
}
connect({
host: '127.0.0.1',
port: 3306,
username: 'root',
password: 'root',
type: 'master'
});
3.2正则表达式命名捕获组
ES9 允许命名捕获组使用符号?< name >,这样获取捕获结果可读性更强
let str = '<a href="http://www.cqu.com">重庆大学</a>';
const reg = /<a href="(?<url>.*)">(?<text>.*)<\/a>/;
const result = reg.exec(str);
console.log(result.groups.url);
console.log(result.groups.text)
3.3正则表达式正反向断言
ES9 支持正反向断言,通过对匹配结果前面的内容进行判断,对匹配进行筛选。
//声明字符串
let str = 'JS4438753 国士无双 522 一路走好';
//正向断言
const reg = /\d+(?=一)/;
const result = reg.exec(str);
//反向断言
const reg = /(?<=双)\d+/;
const result = reg.exec(str);
console.log(result)
四.ECMASript 10 新特性
4.1Object.fromEntries
将数组转化为对象,可以看作entries的逆运算
const m = new Map();
m.set('name', '重庆大学');
const result = Object.fromEntries(m);
console.log(result);
4.2 trimStart 和 trimEnd
trimStart——清除字符串左边的空白;
trimEnd——清除字符串右边的空白;
4.3Array.prototype.flat
//将多维数组转化为低位数组
// const arr = [1,2,3,4,[5,6]];
const arr = [1,2,3,4,[5,6,[7,8,9]]];
//参数为深度是一个数字
console.1og(arr. flat(2));
4.4.Symbol.prototype.description
//创建Symbol
let s = Symbol('重庆大学');
console . log(s.description)//重庆大学