# ES10 —— 新增知识点(stringify,flat,trimStart,matchAll,fromEntries,BigInt...)

因为ES10是对整体原型对象的增强和对语法进行了些修正,没有一块新的内容,是对原来的内容进行升级,细微的东西比较多,所以就写在一起了...

# JSON

# stringify

JSON.stringifyES10 修复了对于一些超出范围的 Unicode 展示错误的问题。因为 JSON 都是被编码成 UTF-8,所以遇到 0xD800–0xDFFF 之内的字符会因为无法编码成 UTF-8 进而导致显示错误。

升级之后:在 ES10 它会用转义字符的方式来处理这部分字符而非编码的方式,这样就会正常显示了。

console.log(JSON.stringify('\u{D800}'))
//"\ud800"
JSON.stringify('\u{D800}') === '"\\ud800"' // true
1
2
3

# Array

# flat

  • 将数组扁平化输出(降维处理)
  • 作用:会按照一个可指定的深度递归遍历数组,并将所有的元素与遍历到的子数组合并成一个新数组返回
  • 默认是一次,如果要递归深度要提升,那么要在flat里面传参数 arr.flat(depth)
let arr = [1, [2, 3], [4, 5, [6, 7]]]
console.log(arr.flat())
// [1, 2, 3, 4, 5, [6, 7]]

// 带参数,深度为2
console.log(arr.flat(2))
// [1, 2, 3, 4, 5, 6, 7]
1
2
3
4
5
6
7

# flatMap

首先什么是map

let array = [1, 2, 3]
console.log(array.map(item => item * 2))
// [2, 4, 6]
1
2
3

flatMap相当于map+flat,如果需要先对这个数组进行map再进行flat操作,就可以直接使用flatMap

console.log(array.flatMap(item => [item * 2]))
// [2, 4, 6]
// 等价于下面

console.log(array.map(item => [item * 2]))
// [[2], [4], [6]]
console.log(array.map(item => [item * 2]).flat())
// [2, 4, 6]
1
2
3
4
5
6
7
8

MDN上面有一个例子来说明两者的不同

let arr = ['今天天气不错', '', '早上好']
arr.map(s => s.split(''))
// [["今", "天", "天", "气", "不", "错"],[""],["早", "上", "好"]]
arr.flatMap(s => s.split(''))
// ["今", "天", "天", "气", "不", "错", "", "早", "上", "好"]
1
2
3
4
5

# String

# trimStart(trimLeft) / trimEnd(trimRight)

trim是字符串去空格方法,这里是控制从左边去空格还是右边去空格。

let str = '   foo   '
1

ES5

// 首尾的空格都去掉
console.log(str.trim())
// 前面的空格进行去掉
console.log(str.replace(/^\s+/g, ''))
// 前面和后面的空格都去掉
console.log(str.replace(/^\s+|\s+$/g, ''))
1
2
3
4
5
6

ES10

// 去掉字符串前面的空格
console.log(str.trimStart())
// or
console.log(str.trimLeft())

// 去掉字符串后面的空格
console.log(str.trimEnd())
// or
console.log(str.trimRight())
1
2
3
4
5
6
7
8
9

# matchAll

let str = `"foo" and "bar" and "baz"`
1

如何把foo,bar,baz提取出来?

# ES5

# 方法一: RegExp.prototype.exec() with /g
  • 因为match方法只能匹配一个,所以要用一个while循环
  • 必须要进行全局匹配,不然每次都是从头开始匹配
function select(regExp, str) {
  const matches = []
  // 因为match方法只能匹配一个,所以要用一个while循环
  while(true){
    const match = regExp.exec(str)
    if(match === null) break
    // 将捕获的第一个输入进数组
    matches.push(match[1])
  }
  return matches
}

// 必须要进行全局匹配,不然每次都是从头开始匹配
// 小括号是捕获,只要不是双引号,就捕获进来
console.log(select(/"([^"]*)"/g, str))
// ["foo", "bar", "baz"]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

这样写比较繁琐,还有没有别的方法?

# 方法二:String.prototype.match() with /g
console.log(str.match(/"([^"]*)"/g))
// [""foo"", ""bar"", ""baz""]
1
2

上面的方法会把所有的捕获都扔掉,只取完整的匹配,所以每个都多了双引号

# 方法三:String.prototype.replace()
function select (regExp, str) {
  const matches = []
  // replace的高级用法,第二个参数可以传一个函数
  str.replace(regExp, function (all, first) {
    matches.push(first)
  })
  return matches
}

console.log(select(/"([^"]*)"/g, str))
// ["foo", "bar", "baz"]
1
2
3
4
5
6
7
8
9
10
11

# ES10的matchAll

let str = `"foo" and "bar" and "baz"`

function select(regExp, str) {
  const matches = []
  // matchAll返回的是可遍历的所有匹配结果 RegExpStringIterator{}
  // 我们对所有的结果做遍历
  for (const match of str.matchAll(regExp)) {
    matches.push(match[1])
  }
  return matches
}

console.log(select(/"([^"]*)"/g, str))
// ["foo", "bar", "baz"]
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# Object

# fromEntries

对象和数组怎么互相转换?

  • 对象转数组 —— entries
  • 数组转对象 —— fromEntries

fromEntriesentries是相对的,并且需要遵循固定的格式。

// 数组转对象 —— entries
const obj = {'foo':'a','bar':'b'}
console.log(Object.entries(obj))
//[["foo", "a"],["bar", "b"]]

// 数组转对象 —— fromEntries
const array = ['foo','bar','baz']
console.log(Object.fromEntries(array)) // 这样会报错必须是固定格式

// 正确写法:
const array = [["foo", "a"],["bar", "b"]]
console.log(Object.fromEntries(array))
// {foo: "a", bar: "b"}
1
2
3
4
5
6
7
8
9
10
11
12
13

# 例子一

如果要访问[['foo', 1], ['bar', 2]]数组中bar的值怎么办?

ES5

const arr = [['foo', 1], ['bar', 2]]
console.log(arr[1][1])
// 2
1
2
3

ES10

const arr = [['foo', 1], ['bar', 2]]
const obj = Object.fromEntries(arr)
console.log(obj)
// {foo: 1, bar: 2}
console.log(obj.bar)
// 2
1
2
3
4
5
6

# 例子二

下面对象把键的字符串长度为3的内容保留下来,其他删除,怎么做?

const obj = {
  abc: 1,
  def: 2,
  ghdsk: 3
}
// 然后将数组再转化成对象
let res = Object.fromEntries(
  // entries先把object对象变成数组,然后对数组进行过滤
  Object.entries(obj).filter(([key,val]) => key.length === 3)
)

console.log(res)
// {abc: 1, def: 2}
1
2
3
4
5
6
7
8
9
10
11
12
13

# try.catch

之前catch后面必须要有e异常变量这个参数,有时候并没有必要

try {
...
} catch (e) {
    ...
}
1
2
3
4
5

ES10之后括号可以删掉

try {
 ...
} catch {
  ...
}
1
2
3
4
5

# Symbol

# Symbol.prototype.description

我们知道,Symbol 的描述只被存储在内部的 [[Description]],没有直接对外暴露,我们只有调用 SymboltoString() 时才可以读取这个属性:

const name = Symbol('My name is axuebin')
console.log(name.toString()) // Symbol(My name is axuebin)
console.log(name) // Symbol(My name is axuebin)
console.log(name === 'Symbol(My name is axuebin)') // false
console.log(name.toString() === 'Symbol(My name is axuebin)') // true
1
2
3
4
5

现在可以通过 description 方法获取 Symbol 的描述:

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

# BigInt

新增的第七种基本数据类型,用来处理超过253次方以外的数

console.log(11n);
// 11n
const a = 11n
console.log(typeof a)
// bigint 是数字,可以进行运算
console.log(typeof 11)
// number
1
2
3
4
5
6
7

PS: 七种基本数据类型:

String、Number、Boolean、Null、Undefined、Symbol、BigInt

更新时间: 2021-02-25 00:05