zl程序教程

您现在的位置是:首页 >  前端

当前栏目

【笔记】再学JavaScript ES(6-10)全版本语法——ES10新增

JavaScriptES笔记 版本 10 语法 新增
2023-09-27 14:26:51 时间


ES10对原型对象能力进行了增强

一、JSON

// ES10之前就有,bug:超出Unicode展示错误,例如0xD800-0xDFFF,ES10让这部分转义为非编码方式存在
console.log(JSON.stringify('\u{D800}')) // "\ud800"

二、Array

1.Array.flat

按照一个可指定深度(默认为1)的递归遍历数组,并将所有元素与得到的子元素合并为一个新数组返回

let arr1 = [1, [2, 3], [4, [5, 6, [7, 8]]]]
console.log(arr1.flat(3)) // [1, 2, 3, 4, 5, 6, 7, 8]

2.Array.flatMap

Array.flatMap与Array.map和Array.flat合起来的作用一样,只是只能用于一维数组

let arr2 = [1, 2, 3, 4, 5, 6]
console.log(arr2.map(item => item * 10).flat(3)) // [10, 20, 30, 40, 50, 60]
console.log(arr2.flatMap(item => item * 10)) // [10, 20, 30, 40, 50, 60]

三、String

1.空格替换(首/尾)

let str = '   foo   '
// 老方法
console.log(str.replace(/^\s+|\s+$/g, ''))
// 新方法
console.log('trimLeft', str.trimLeft())
console.log('trimRight', str.trimRight())
console.log('trimStart', str.trimStart())
console.log('trimEnd', str.trimEnd())
console.log('trim', str.trim())

在这里插入图片描述

2.字符串中提取匹配项到指定数组中

let str = `'foo' and 'bar' and 'baz'`
// 方法一:exec
function select1 (regExp, str) {
  const matches = []
  while (true) {
    const match = regExp.exec(str)
    if (match === null) break
    matches.push(match[1]) // 拿到匹配内容(match[0]是包括匹配对象的完整匹配,match[1]才是匹配内容)
  }
  return matches
}
console.log(select1(/'([^']*)'/g, str)) // ["foo", "bar", "baz"]
// 方法二:match
console.log(str.match(/'([^']*)'/g)) // ["foo", "bar", "baz"]
// 方法三:replace
function select2 (regExp, str) {
  const matches = []
  str.replace(regExp, (all, first) => { // 参数all是完整捕获,first是首次捕获
    matches.push(first)
  })
  return matches
}
console.log(select2(/'([^']*)'/g, str)) // ["foo", "bar", "baz"]
// 方法四(新增):matchAll
function select3 (regExp, str) {
  const matches = []
  // 使用matchAll拿到所有捕获,返回RegExpStringIterator迭代器对象,可以使用循环push到数组中使用,不能直接使用
  for (const match of str.matchAll(regExp)) {
    matches.push(match[1])
  }
  return matches
}
console.log(select3(/'([^']*)'/g, str)) // ["foo", "bar", "baz"]
console.log(str.matchAll(/'([^']*)'/g)) // RegExpStringIterator迭代器对象,不能直接使用
  • exec一次只能匹配一个表达式
  • 无全局匹配的话每次都只会从第一个位置匹配

拓展:

四、Object

1.fromEntries

操作过程与Object.entries()相反,把键值对数组为元素的二维数组转换为一个对象

案例1

使用fromEntries将特定格式的数组转对象提高遍历效率

const arr = [['foo', 1], ['bar', 2]]
console.log(arr[1][1]) // 普通遍历低效
const obj = Object.fromEntries(arr)
console.log(obj.bar)

案例2

提取名单中三个字符的键的键值对

对于这种场景,由于数组的API相对对象更多,使用更为灵活,因此可以将对象转为数组进行操作,最后通过fromEntries转回对象形式

const obj = {
  xxx: 1,
  yyy: 2,
  aaaa: 3,
  bbbb: 4,
  zzz: 5,
  cccc: 6
}
let res = Object.fromEntries(
  Object.entries(obj).filter(([key, val]) => key.length === 3)
)
console.log(res) // {xxx: 1, yyy: 2, zzz: 5}

练习

利用Object.fromEntries把url的search部分返回一个object

const url = 'https://www.xxx.com/s?foo=1&bar=2&baz=3&qux=4'
console.log(Object.fromEntries(new URLSearchParams(url.slice('https://www.xxx.com/s?'.length))))
// {foo: "1", bar: "2", baz: "3", qux: "4"}
console.log(Object.fromEntries(new URLSearchParams(url.split('?', 2)[1].toString())))
// {foo: "1", bar: "2", baz: "3", qux: "4"}

// 后面两种不理想
console.log(Object.fromEntries(Object.entries(url.split('?', 2)[1].split(/[&]|[=]/))))
// {0: "foo", 1: "1", 2: "bar", 3: "2", 4: "baz", 5: "3", 6: "qux", 7: "4"}
console.log(Object.fromEntries(Object.entries(url.split('?', 2)[1].split('&').toString().split('='))))
// {0: "foo", 1: "1,bar", 2: "2,baz", 3: "3,qux", 4: "4"}

拓展:

五、Function

Function.toString()方法返回一个表示函数源代码的字符串,给人的感觉还是比较鸡肋的。。。可以看看下面这篇文章:

六、try&catch

ES10之前,try/catch语句中的catch子句需要一个参数。现在,它允许开发人员使用try/catch而不要求必须有error参数。

// 之前
try {
  // ...
} catch (e) {
  // ...
}
// ES10
try {
  // ...
} catch {
  // ...
}

七、BigInt

用来处理2^53以外的数据

console.log(typeof 11n) // bigint
console.log(typeof 11) // number

八、Symbol.Description

在ES10,当创建符号时,可以提供一个字符串作为描述。

console.log(Symbol('myDescription').description) // myDescription
console.log(Symbol.iterator.description) // Symbol.iterator
console.log(Symbol.for('foo').description) // foo

九、标准 globalThis 对象

// 全局 this 在ES10之前尚未标准化,在生产代码中,可以通过以下代码来“标准化”它
let getGlobal = () => {
  if (typeof self !== 'undefined') return self
  if (typeof window !== 'undefined') return window
  if (typeof global !== 'undefined') return global
  throw new Error('找不到全局对象')
}
/** ES10新增了globalThis对象,用来访问任何平台上的全局对象 */
// 访问全局数组构造函数
console.log(globalThis.Array(0, 1, 2)) // [0, 1, 2]
// 相当于
console.log(globalThis.v = { value: true }) // {value: true}

十、哈希标签#

目前不常用,可见: