写在前面
之前写过一篇ES6(纯的)的博客,今天写一下后续。
ES6的改变很大,以至于后面的ES7,ES8等等都统称为'ES6'
,那么今天就让我们来看看ES7-11的一些内容吧。
ES7
Array.prototype.includes
includes
方法用来检测数组中是否包含某个元素,返回布尔类型值
console.log([1, 2, 3].includes(2)); // true
console.log([1, 2, 3].includes(4)); // false
console.log([1, 2, 3].includes(3, 3)); // false
console.log([1, 2, 3].includes(3, -1)); // true
console.log([1, 2, NaN].includes(NaN)); // true
includes()
方法有意设计为通用方法。它不要求this值是数组对象,所以它可以被用于其他类型的对象 (比如类数组对象)。下面的例子展示了 在函数的 arguments
对象上调用的 includes()
方法。
(function() {
console.log([].includes.call(arguments, 'a')); // true
console.log([].includes.call(arguments, 'd')); // false
})('a','b','c');
幂运算**
console.log(2**10)
ES8
async和await
async和await了两种语法结合可以让异步代码像同步代码一样
async函数
async
函数的返回值为promise
对象promise
对象的结果由async
函数执行的返回值决定
await表达式
await
必须写在async
函数中await
右侧的表达式一般为promise
对象await
返回的是promise
成功的值await
的promise
失败了,就会抛出异常,需要通过try...catch
捕获处理
Object.values,keys和Object.entries
- 1.
Object.values()
方法返回一个给定对象的所有可枚举属性值的数组
(keys
同理,返回的是键名)
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.values(obj)); // ['a', 'b', 'c']
比如找到map中值为1的下标
let map = new Map()
map.set(1, 1)
map.set(2, 3)
let arr = [...map.values()]
arr.forEach((item, index) => {
if (item == 1) {
console.log(index) // 0
}
})
- 2.
Object.entries()
方法返回一个给定对象自身可遍历属性[key,value]的数组
让obj的遍历变得更加丝滑…
const object1 = {
a: 'somestring',
b: 42
};
for (const [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
Object.getOwnPropertyDescriptors
该方法返回指定对象所有自身属性的描述对象
const obj = Object.create(null, {
name: {
value: '41',
writable: true,
configurable: true,
enumerable: true
}
})
console.log(Object.getOwnPropertyDescriptors(obj));
ES9
扩展运算符与rest参数
Resr参数与spread扩展运算符在ES6中已经引入,不过ES6中只针对于数组,在ES9中为对象提供了像数组一样的rest参数和扩展运算符
function test ({ name, age, ...other }) {
console.log(name);
console.log(age);
console.log(other);
}
test({
name: 41,
age: 24,
type: 123,
username: 123,
password: 123
})
/*
41
24
{ type: 123, username: 123, password: 123 }
*/
对象的扩展运算符之合并
const skillone = {
q: 1
}
const skilltwo = {
w: 2
}
console.log({ ...skillone, ...skilltwo });
正则扩展:命名捕获分组
?<>
let str = '<a href="http://www.baidu.com">bit</a>'
// const reg = /<a href="(.*)">(.*)<\/a>/
const reg = /<a href="(?<url>.*)">(?<text>.*)<\/a>/
const res = reg.exec(str)
console.log(res.groups.url);
console.log(res.groups.text);
正则扩展: 反向断言
let str = 'dasdsada123哈哈哈456零零零零'
// 正向断言
// const reg = /\d+(?=零)/
// const res = reg.exec(str)
// 反向断言
const reg = /(?<=哈)\d+/
const res = reg.exec(str)
console.log(res);
正则扩展:dotAll模式
正则表达式中,点(.)是一个特殊字符,代表任意的单个字符,但是行终止符(line terminator character)除外。
引入一个s
修饰符来解决了这个问题
ES10
Object.fromEntries
可以说是entries
的逆运算,把键值对转换成对象
const entries = new Map([
['foo', 'bar'],
['baz', 42]
]);
const obj = Object.fromEntries(entries);
console.log(obj);
// expected output: Object { foo: "bar", baz: 42 }
trimStart与trimEnd
trimStart()
清除字符串前面的空白字符trimEnd()
清除字符串后面的空白字符
flat与flatMap
flat
数组扁平化
var arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]
var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]
var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]
//使用 Infinity,可展开任意深度的嵌套数组
var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- flatMap 方法与 map 方法和深度depth为1的 flat 几乎相同.
let arr = [1, 2, 3, 4]
let res1 = arr.map(x => [x * 2])
let res2 = arr.flatMap(x => [x * 2])
console.log(res1);//[ [ 2 ], [ 4 ], [ 6 ], [ 8 ] ]
console.log(res2);//[ 2, 4, 6, 8 ]
Symbol.prototype.description
console.log(Symbol('desc').description);
// expected output: "desc"
ES11
私有属性
简单来说就是在class
里面的属性前面加一个#
就和c++里面的private
一样
不过多阐述了!
Promise.allSettled
解决了Promise.all,有一个坏了就全坏了的情况!
const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));
const promises = [promise1, promise2];
Promise.allSettled(promises).
then((results) => results.forEach((result) => console.log(result.status)));
// expected output:
// { status: 'fulfilled', value: 3 }
// { status: 'rejected', reason: 'foo' }
String.prototype.matchAll
matchAll()
方法返回一个包含所有匹配正则表达式的结果及分组捕获组的迭代器,这样就可以使用of
迭代了
let str = `<ul>
<li>
<a>123</a>
<p>456</p>
</li>
<li>
<a>789</a>
<p>987</p>
</li>
</ul>`
const reg = /<li>.*?<a>(?<texta>.*?)<\/a>.*?<p>(?<textp>.*?)<\/p>/sg
const result = str.matchAll(reg)
for (let v of result) {
console.log(v.groups.texta);
console.log(v.groups.textp);
}
可选链操作符?.
?.
让我们不用去判断是否存在了
方便我们的链式调用
// ES2019的写法
function doSomething(onContent, onError) {
try {
// ... do something with the data
}
catch (err) {
if (onError) { // 校验onError是否真的存在
onError(err.message);
}
}
}
/******************************************/
// 使用可选链进行函数调用
function doSomething(onContent, onError) {
try {
// ... do something with the data
}
catch (err) {
onError?.(err.message); // 如果onError是undefined也不会有异常
}
}
空值合并运算符??
空值合并操作符(??)是一个逻辑操作符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。
let res1 = 0 ?? 42
let res2 = 0 || 42
console.log(res1);
console.log(res2);
BigInt类型
BigInt 是一种内置对象,它提供了一种方法来表示大于 2^53 - 1 的整数。这原本是 Javascript中可以用 Number 表示的最大数字。BigInt 可以表示任意大的整数。
const previousMaxSafe = BigInt(Number.MAX_SAFE_INTEGER);
// ↪ 9007199254740991n
const maxPlusOne = previousMaxSafe + 1n;
// ↪ 9007199254740992n
const theFuture = previousMaxSafe + 2n;
// ↪ 9007199254740993n, this works now!
const multi = previousMaxSafe * 2n;
// ↪ 18014398509481982n
const subtr = multi – 10n;
// ↪ 18014398509481972n
const mod = multi % 10n;
// ↪ 2n
const bigN = 2n ** 54n;
// ↪ 18014398509481984n
bigN * -1n
// ↪ –18014398509481984n
globalThis
全局属性 globalThis 包含全局的 this 值,类似于全局对象(global object)。