ES7、ES8、ES9、ES10、ES11、ES12都增加了哪些新特性?
// 1. async function
const promise = () => {
console.log(1);
return new Promise((resolve, reject) => {
resolve(2);
});
};
const asyncFunc = async () => {
console.log(3);
const test = await promise();
console.log("4", test);
};
asyncFunc(); // 3 1 4 2
// 2. Object.entries
let obj = { a: 1, b: 2 };
console.log(111, Object.entries(obj)); // => [ [ 'a', 1 ], [ 'b', 2 ] ]
// 3. Object.values
console.log(222, Object.values(obj)); // => [1,2]
// 4. Object.getOwnPropertyDescriptors 获取一个对象所有自身属性的描述符
console.log(333, Object.getOwnPropertyDescriptors(obj));
// => {
// a: { value: 1, writable: true, enumerable: true, configurable: true },
// b: { value: 2, writable: true, enumerable: true, configurable: true }
// }
// 异步迭代器
const asyncIterator = () => {
const arr = [1, 2];
return {
next: () => {
if (arr.length) {
return Promise.resolve({
value: arr.shift(),
done: false,
});
}
return Promise.resolve({
done: true,
});
},
};
};
let iterator = asyncIterator();
const test = async () => {
await iterator.next().then((res) => {
console.log(res); // { value: 1, done: false }
});
await iterator.next().then((res) => {
console.log(res); // {value: 2, done: false}
});
await iterator.next().then((res) => {
console.log(res); // {done: true}
});
};
test();
console.log("=============================");
// for-await-of 在循环中异步调用函数
const promises = [
new Promise((resolve, reject) => resolve(1)),
new Promise((resolve, reject) => resolve(2)),
new Promise((resolve, reject) => resolve(3)),
];
const test2 = async () => {
for await (const p of promises) {
console.log("p", p); // 1,2,3
}
};
test2();
// Object rest properties
let test3 = {
a: 1,
b: 2,
c: 3,
d: 4,
};
let { a, b, ...reset } = test3;
console.log("===", a, b, reset); // => 1 2 { c: 3, d: 4 }
// Promise.prototype.finally finally 方法都会被调用
const promise2 = new Promise((resolve, reject) => {
resolve("resolved");
reject("rejected");
});
promise2
.then((res) => {
console.log("res", res);
})
.finally(() => {
console.log("finally");
});
// Array.prototype.flat 扁平化嵌套数组
const arr = [1, 2, [[[[3, 4]]]]];
console.log(arr.flat(Infinity)); // [ 1, 2, 3, 4 ]
// flatMap
const arr1 = ["it's Sunny in", "", "California"];
const arr2 = arr1.map((x) => x.split(" "));
console.log("arr2", arr2); // [ [ "it's", 'Sunny', 'in' ], [ '' ], [ 'California' ] ]
const arr3 = arr1.flatMap((x) => x.split(" "));
console.log("arr3", arr3); // [ "it's", 'Sunny', 'in', '', 'California' ]
// formEntries 键值对列表转换成一个对象
let map = new Map([
["a", 1],
["b", 2],
]);
let mapToObj = Object.fromEntries(map);
console.log(mapToObj); // {a: 1, b: 2}
// try catch
try {
console.log(p);
} catch (error) {
console.log("===p is error");
}
参考链接1 - 作者:南殇:掘金
参考链接2:MDN