【ES10系列】新特性汇总

JSON.stringify() 能力补足

0xD800-0xDFFF 这个区间的字符会因为无法编码成 UTF-8 而导致显示错误,ES10对这个错误进行了修正。运用转义字符的方式,让这个区间的字符以非编码的方式存在,保证正常显示。

Array.flat() 数组扁平化处理

flat() 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。传入参数指定要提取嵌套数组的结构深度,默认值为 1

// 扁平化输出
// 之前的解决方案:递归 或 toString()
// ES10 新增api flat()
let arr = [1, [2, 3],
  [4, 5, [6, 7, [8, 9]]]
]
console.log(arr.flat()) // [1, 2, 3, 4, 5, Array(2)]
console.log(arr.flat(2)) // [1, 2, 3, 4, 5, 6, 7, Array(2)]
console.log(arr.flat(3)) //  [1, 2, 3, 4, 5, 6, 7, 8, 9]

 Array.flatMap()

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

flatMap() 方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。从方法的名字上也可以看出来它包含两部分功能一个是 map,一个是 flat(深度为1)

语法:const new_array = arr.flatMap(function callback(currentValue[, index[, array]]) {// 返回新数组的元素}[, thisArg])

参数含义必选
callback可以生成一个新数组中的元素的函数,可以传入三个参数:currentValue、index、arrayY
thisArg遍历函数 this 的指向N

String.prototype.trimStart()或String.prototype.trimLeft()

去除字符串开头的空格。

String.prototype.trimEnd()或String.prototype.trimRight()

去除字符串结尾的空格。

String.prototype.trim()

去除字符串首尾空格。

String.prototype.matchAll()

// 业务场景描述:找出带引号的单词 ES5实现方法

// 第一种方法
let str = `"foo" and "bar" and "baz"`

function select(regExp, str) {
  const matches = []
  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"]


// 第二种方法
console.log(str.match(/"([^"]*)"/g)) // [""foo"", ""bar"", ""baz""]
// 用match 方法,如果使用g进行全局匹配,返回结果将会丢弃捕获,只返回完整的匹配


// 第三种方法 replace
// replace 第二个参数可以传一个函数,函数接收两个参数,第一个完整匹配,第二个捕获
function select(regExp, str) {
  const matches = []
  str.replace(regExp, function (all, first) {
    matches.push(first)
  })
  return matches
}
console.log(select(/"([^"]*)"/g, str)) // ["foo", "bar", "baz"]

 

function select(regExp, str) {
  const matches = []
  for (const match of str.matchAll(regExp)) {
    matches.push(match[1])
  }
  return matches
}
console.log(select(/"([^"]*)"/g), str);

Object.fromEntries()

键值对列表转换为一个对象,这个方法是和 Object.entries() 相对的。

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

// 业务场景描述:筛选出key长度为3的数据

const obj = {
  abc: 1,
  def: 2,
  ewer: 3
}
// 先把obj对象转换成键值对形式的数组,再运用数组的方法对键值进行过滤
let res = Object.fromEntries(
  Object.entries(obj).filter(([key, val]) => key.length === 3)
)
console.log(res) // {abc: 1, def: 2}

try…catch 能力增强

// try...catch 语法
try {

} catch (e) {

}
// ES10 可以省略 catch参数
try {

} catch{

}

BigInt

新增数据类型。用于处理超过2^53的数,之前的js处理能力只能处理2^53以内的数。可以进行四则运算

const a = 11n
typeof a //bigint

思考:

1、如何给Array 实现一个 Flat 函数?

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值