1. ES7 – 2016
1. 数组的includes方法
- 数组中是否包含某个元素,返回值为boolean
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr.includes(5); // true
2. ** 幂次方
let res = 2 ** 3; // 8
2. ES8 --2017
1. 字符串补全
- 基本使用
let str = '123';
str.padStart(5, 'A'); // AA123
str.padEnd(5, 'A'); // 123AA
str.padStart(5, 'ABCD'); // AB123
str.padEnd(5, 'ABCD'); // 123AB
str.padStart(10, 'ABC'); // ABCABCA123
str.padEnd(10, 'ABC'); // 123ABCABCA
- 指定位置补全
2. Object.values和Object.entries
- 类似于
map.values()
,map.entries()
,map.keys()
let obj = { name: "zhangsan", age: 18, sex: "male" }
let keys = Object.keys(obj) // [ 'name', 'age','sex' ]
// 获取对象的value,并转换为数组
let values = Object.values(obj) // [ 'zhangsan', 18,'male' ]
// 将对象转换为二维数组
let entries = Object.entries(obj) // [ [ 'name', 'zhangsan' ], [ 'age', 18 ], ['sex','male' ] ]
// 转换为map结构
let map = new Map(Object.entries(obj))
console.log(map); // Map(3) { 'name' => 'zhangsan', 'age' => 18,'sex' =>'male' }
3. async…await
async...await
与Promise
紧密相连
- async定义的函数为异步函数,如有返回值,则返回值一定是
Promise
async function myAsyncFunction() {
return "Hello, world!"
}
console.log(myAsyncFunction()) // Promise {<fulfilled>: 'Hello, world!'}
-
await
:等待,在await
之后的代码需要等待await
代码有结果后继续执行 -
await
定义Promise
:等待Promise状态发生改变- 如果状态变为成功,返回Promise的结果;
- 如果状态变为失败,则由catch捕获错误
function getPromise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
// reject('Promise rejected!');
resolve('Promise resolved!');
},1000);
});
}
async function myAsyncFunction() {
try {
// result接收promise成功后的返回值
const result = await getPromise()
console.log("必须等待await完成,并且promise状态为fulfilled,才能执行下面的代码")
console.log(result);
} catch (error) {
console.error(error);
}
}
myAsyncFunction();
- promise.then
function getPromise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
// reject('Promise rejected!');
resolve('Promise resolved!');
},1000);
});
}
async function myAsyncFunction() {
try {
const result = await getPromise().then(value => {
console.log("Inside then:", value); // Inside then: Promise resolved!
return value+"then处理后返回的数据";
});
console.log("After then:", result); //After then: Promise resolved!then处理后返回的数据
} catch (error) {
console.error(error);
}
}
myAsyncFunction();
3. ES9 – 2018
1. promise的catch
作用:当
promise
状态变为fulfilled
,then
执行成功的回调,但是在回调中产生的异常没有处理方式
- catch可以捕获所有的异常,无论是
promise
还是then
里面产生的 - 如果没有错误的回调,
catch
也能接收rejected
状态
let promise = new Promise((resolve, reject) => {
// throw new Error("错误")
// resolve("成功")
reject("失败")
});
promise.then(value => {
throw new Error("错误")
console.log(value) // 成功
})
.catch(err => {
console.log("catch:",err) // 失败
})
2. promise的finally
- 最后总会执行的代码
promise.then(value => {
console.log(value) // 成功
}).finally(() => {
console.log("finally")
})
3. await 和 for…of
- 一起开始,按数组的顺序返回
// await 和 for...of
function getData(setTime) {
return new Promise((resolve, reject) => {
console.log(setTime+"开始");
setTimeout(() => {
resolve(setTime);
}, setTime);
});
}
async function fun(){
// 一起开始执行,返回时按数组的顺序
for await(let item of [getData(2000),getData(5000),getData(1000)]){
console.log(item);
}
}
fun();
- 按数组顺序前面的结束才开始后面的,等全部执行完毕后同时返回
- 像
Promise.all
方法
async function fun(){
// 一起开始执行,返回时按数组的顺序
for (let item of [await getData(2000),await getData(3000),await getData(1000)]){
console.log(item);
}
}
- 不使用
await
:一起开始,谁先完成谁先返回
async function fun(){
// 一起开始执行,返回时按数组的顺序
for (let item of [ getData(2000), getData(3000), getData(1000)]){
item.then((res)=>{
console.log(res);
});
}
}
4.ES10 – 2019
1. 字符串去前或后空格
let str = " hello world "
// 去除字符串前后空格
str.trim() // "hello world"
// 去除字符串前空格
str.trimStart() // "hello world "
// 去除字符串后空格
str.trimEnd() // " hello world"
2. 转化为对象形式Object.fromEntries()
// 二位数组转对象
let arr = [["name", '张三'], ["age", 18], ["sex", '男']]
let obj = Object.fromEntries(arr)
console.log(obj) // {name: '张三', age: 18, sex: '男'}
// Map 转对象
let map = new Map([["name", '张三'], ["age", 18], ["sex", '男']])
let obj = Object.fromEntries(map)
console.log(obj) // {name: '张三', age: 18, sex: '男'}
let queryParams = "?name=张三&age=18&sex=男"
let params = new URLSearchParams(queryParams)
let obj = Object.fromEntries(params)
console.log(obj) // {name: '张三', age: '18', sex: '男'}
3. 扁平化数组flat
let arr = [1,[2,3],[4,[5]]]
// 默认只能扁平化二维数组
console.log(arr.flat()) // [1,2,3,4,[5]]
// 参数:扁平化的层数
console.log(arr.flat(2)) // [1,2,3,4,5]
// 不管是几维数组,都可以扁平化为一维数组
console.log(arr.flat(Infinity)) // [1,2,3,4,5]
- 可以去除数组中的空元素
let arr = [1,2,,4,,6,,8,9,10]
console.log(arr.flat()) // [1,2,4,6,8,9,10]
4. 扁平化并遍历元素flatMap
- 最多二维数组,
let arr = [1,2,3,[4],5]
let arr1 = arr.flatMap(item => item%2==0?item:[])
console.log(arr1); // [2, 4]
5. ES11 – 2020
1. 字符串查找,返回迭代器
let str = `
<ul>
<li>第一条新闻</li>
<li>第二条新闻</li>
<li>第三条新闻</li>
</ul>
`
let reg = /<li>(.*)<\/li>/g;
let res = str.matchAll(reg);
for (let item of res) {
console.log(item[1]);
}
/*
第一条新闻
第二条新闻
第三条新闻
*/
2. Promise.allSettled
- 无论成功失败都会执行then的成功回调
let p1 = new Promise((resolve, reject)=>{
setTimeout(resolve,2000,"P1")
})
let p2 = new Promise((resolve, reject)=>{
setTimeout(resolve,1000,"P2")
})
let p3 = new Promise((resolve, reject)=>{
setTimeout(resolve,3000,"P3")
})
Promise.allSettled([p1,p2,p3]).then(res=>{
console.log(res)
})
3. 动态导入import()
// 在需要时导入,import返回promise
import('./module.js').then(res => {
console.log(res.var1)
})
let res = await import('./module.js')
console.log(res.var1)
6. ES12 – 2011
1. 字符串中字符替换(全部替换)
let str = 'aabbcc'
let str1 = str.replaceAll('b', 'MM')
console.log(str1) // aaMMMMcc
2. Null 赋值运算符 ??
let id = 1
let x = id ?? 101
console.log(x) // 1
let id = null
let x = id ?? 101
console.log(x) // 101
3. 数字分隔符,提高可读性
let num1 = 111222333444
let num2 = 111_222_333_444
console.log(num1 === num2);
4. Promise.any
- 谁先成功,执行then的成功回调
let p1 = new Promise((resolve, reject)=>{
setTimeout(resolve,2000,"P1")
})
let p2 = new Promise((resolve, reject)=>{
setTimeout(resolve,1000,"P2")
})
let p3 = new Promise((resolve, reject)=>{
setTimeout(resolve,3000,"P3")
})
Promise.any([p1,p2,p3]).then(res=>{
console.log(res) // P2
},err=>{
console.log(err)
})
- 全部失败,执行then的失败回调
let p1 = new Promise((resolve, reject)=>{
setTimeout(reject,2000,"P1")
})
let p2 = new Promise((resolve, reject)=>{
setTimeout(reject,1000,"P2")
})
let p3 = new Promise((resolve, reject)=>{
setTimeout(reject,3000,"P3")
})
Promise.any([p1,p2,p3]).then(res=>{
console.log(res)
},err=>{
console.log(err) // AggregateError: All promises were rejected
})
7. ES13 – 2022
1. 数组的at方法
- at的参数可以为负数
let arr = [a,b,c,d,e];
arr.at(-2) // d
2. Object.hasOwn()对象中是否包含某个属性
let obj = {
name: "Rahul",
age: 23,
gender: "male"
}
console.log(Object.hasOwn(obj, "name"));