ES2019 重点总结

1.Array.prototype.flat()

Array.prototype.flat()用于将嵌套的数组“拉平”,变成一维的数组。该方法返回一个新数组,对原数据没有影响。flat(depth),flat()默认只会“拉平”一层,如果想要“拉平”多层的嵌套数组,可以将flat()方法的参数写成一个整数,表示想要拉平的层数,depth默认为1。

const arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]

const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

const arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

// 如果不管有多少层嵌套,都要转成一维数组,可以用Infinity关键字作为参数。
const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// 如果原数组有空位,flat()方法会跳过空位。
[1, 2, , 4, 5].flat()
// [1, 2, 4, 5]

2.Array.prototype.flatMap()

flatMap() 方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。
它与 map 连着深度值为1的 flat 几乎相同,但 flatMap 通常在合并成一种方法的效率稍微高一些。

[1, 2, 3, 4].flatMap((x) => [x * 2])
// [2, 4, 6, 8]

// 相当于先map再flat()
[1, 2, 3, 4].map(x => [x * 2]).flat()
// [2, 4, 6, 8]

3.String.prototype.trimStart()

trimStart() 方法从字符串的开头删除空格,trimLeft()是此方法的别名。
返回一个新字符串,表示从其开头(左端)除去空格的调用字符串。

var str = "   foo  ";
console.log(str.length); // 8
str = str.trimStart()    // 等同于 str = str.trimLeft();
console.log(str.length); // 5
console.log(str);        // "foo  "

4.String.prototype.trimEnd()

trimEnd() 方法从一个字符串的末端移除空白字符。trimRight() 是这个方法的别名。
返回一个新字符串,表示从调用字串的末(右)端除去空白。

var str = "   foo  ";
console.log(str.length); // 8
str = str.trimRight();  // 或写成str = str.trimEnd();
console.log(str.length); // 6
console.log(str);       // '   foo'

5.String.prototype.matchAll()

matchAll() 方法返回一个包含所有匹配正则表达式的结果及分组捕获组的迭代器。
在 matchAll 出现之前,通过在循环中调用 regexp.exec() 或 string.match()来获取所有匹配项信息(其中regexp 必需使用 /g 标志)

before

// 方法1
function collectGroup1 (regExp, str) {
  const matches = []
  while (true) {
  	
    const match = regExp.exec(str)
    // 其中regexp 必需使用 /g 标志,否则每次都重新从第一位开始,容易陷入死循环
    if (match === null) break
    // Add capture of group 1 to `matches`
    matches.push(match[1])
  }
  return matches
}

collectGroup2(/"([^"]*)"/g, `"foo" and "bar" and "baz"`)
// [ 'foo', 'bar', 'baz' ]

// 方法2
// str.replace()除了支持字符串还支持函数
function collectGroup1 (regExp, str) {
  const matches = []
  function replacementFunc (all, first) {
    matches.push(first)
  }
  str.replace(regExp, replacementFunc)
  return matches
}

collectGroup2(/"([^"]*)"/ug, `"foo" and "bar" and "baz"`)
// ["foo", "bar", "baz"]
// 如果没有 flag /g, .exec() 只返回第一个匹配
let re = /[abc]/
re.exec('abc')
// ["a", index: 0, input: "abc", groups: undefined]
re.exec('abc')
// ["a", index: 0, input: "abc", groups: undefined]

after

有了matchAll之后

function collectGroup3 (regExp, str) {
  let results = []
  for (const match of str.matchAll(regExp)) {
    results.push(match[1])
  }
  return results
}
collectGroup3(/"([^"]*)"/g, `"foo" and "bar" and "baz"`)
// ["foo", "bar", "baz"]

6.Object.fromEntries()

Object.fromEntries() 方法把键值对列表转换为一个对象。

// 例1:
Object.fromEntries([['foo', 1], ['bar', 2]])
// {foo: 1, bar: 2}

// 例2
const entries = new Map([
  ['foo', 'bar'],
  ['baz', 42]
]);
const obj = Object.fromEntries(entries);
console.log(obj);
// { foo: "bar", baz: 42 }

更普遍的使用场景是和Entries搭配用:
先使用Object.entries将对象转为数组,使用数组方法处理完数据后,再使用Object.fromEntries转换为对象。

// 仅保留对象中属性名长度等于3的部分,并将其属性值变为原来的2倍
let obj = { abc: 1, def: 2, ghij: 3 }
let res = Object.fromEntries(
  Object.entries(obj)
    .filter(([ key, val ]) => key.length === 3)
    .map(([ key, val ]) => [ key, val * 2 ])
)
console.log(res)
// res is { 'abc': 2, 'def': 4 }

7.Symbol.prototype.description

description 是一个只读属性,它会返回 Symbol 对象的可选描述的字符串。

const name = Symbol('My name is axuebin')
console.log(name.description) // My name is axuebin

console.log(Symbol('desc').description);
// "desc"

console.log(Symbol.iterator.description);
// "Symbol.iterator"

8.Function.prototype.toString()

toString() 方法返回一个表示当前函数源代码的字符串

function sum(a, b) {
  return a + b;
}

console.log(sum.toString());

// "function sum(a, b) {
//   return a + b;
// }"

9.try…catch

ES2019之后,可省略 catch 的 err 参数

// before
try {
  // ...
} catch (err) {
  // ...
}

// after:现在可省略err这个参数
try {
  // ...
} catch {
  // ...
}

10.BigInt

ES2019 增加了一个数据类型:BigInt,用于处理超过 2^53 - 1的数字。这原本是 Javascript中可以用 Number 表示的最大数字。BigInt 可以表示任意大的整数。

在一个整数字面量后面加 n 的方式定义一个 BigInt ,如:10n,或者调用函数BigInt()。

const theBiggestInt = 9007199254740991n;
// 9007199254740991n
const alsoHuge = BigInt(9007199254740991);
// 9007199254740991n
const hugeString = BigInt("9007199254740991");
// 9007199254740991n
const hugeHex = BigInt("0x1fffffffffffff");
// 9007199254740991n
const hugeBin = BigInt("0b11111111111111111111111111111111111111111111111111111");
// 9007199254740991n

注意:
不能用于 Math 对象中的方法;
不能和任何 Number 实例混合运算,两者必须转换成同一种类型。
BigInt 与普通整数是两种值,它们之间并不相等。

// BigInt 和 Number 不是严格相等的,但是宽松相等的。
42n === 42 // false
42n == 42 // true

并且在两种类型来回转换时要小心,因为 BigInt 变量在转换成 Number 变量时可能会丢失精度。

BigInt(123) // 123n
BigInt('123') // 123n
BigInt(false) // 0n
BigInt(true) // 1n

Boolean(0n) // false
Boolean(1n) // true
Number(1n)  // 1
String(1n)  // "1"
!0n // true
!1n // false

使用 typeof 测试时, BigInt 对象返回 “bigint” :

typeof 1n === 'bigint'; // true

typeof BigInt('1') === 'bigint'; // true

对任何 BigInt 值使用 JSON.stringify() 都会引发 TypeError,因为默认情况下 BigInt 值不会在 JSON 中序列化。但是,如果需要,可以自定义实现BigInt.prototype.toJSON 方法。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值