16.(ECMAScript)es10完全解读

1. 重点提炼

  • Object.fromEntries()
  • String扩展
  • Array扩展
  • Function修正
  • 优化捕获异常——可选的Catch Binding
  • JSON扩展
  • Symbol扩展

2. 对象扩展:Object.fromEntries()

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

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

即将对象转为数组的形式,并且为keyvalue的二维数组形式。

const obj = {
    name: 'QH',
    course: 'es'
}
const entries = Object.entries(obj)
console.log(entries)

image-20201129105250927

参考:https://github.com/6xiaoDi/blog-ECMScript-Series/tree/a3.92
Branch: branch02

commit description:a3.92(对象扩展:Object.fromEntries()——Object.entries)

tag:a3.92


2.1 Object 转换操作

es10提供了新的方法 =>

Object.fromEntries()Object.entries() 逻辑是相反的。

键值对形式的二维数组,转为键值对形式的对象。

const obj = {
    name: 'QH',
    course: 'es'
}
const entries = Object.entries(obj)
console.log(entries)

// ES10
const fromEntries = Object.fromEntries(entries)
console.log(fromEntries)

image-20201129142502288

参考:https://github.com/6xiaoDi/blog-ECMScript-Series/tree/a3.93
Branch: branch02

commit description:a3.93(对象扩展:Object.fromEntries()——基本用法)

tag:a3.93


2.2 Map 转 Object

可将map转为键值对的对象。

// map -> 对象
const map = new Map()
map.set('name', 'QH')
map.set('course', 'es')
console.log(map)
const fromEntries = Object.fromEntries(map)
console.log(fromEntries)

image-20201129142758777

参考:https://github.com/6xiaoDi/blog-ECMScript-Series/tree/a3.94
Branch: branch02

commit description:a3.94(对象扩展:Object.fromEntries()——可将map转为键值对的对象)

tag:a3.94


2.3 过滤

找到对象中成绩大于80分的属性(科目),过去的话需要循环迭代每一项,并做逻辑判断,再取出。

es当中数组的方法显然比对象的多,因此可以把对象转为键值对的数组,再过滤出成绩大于80分的即可,最后可把结果数组转回结果对象。

const course = {
    math: 80,
    english: 85,
    chinese: 90
}
const res = Object.entries(course).filter(([key, val]) => val > 80)
console.log(res)
console.log(Object.fromEntries(res))

image-20201129145423709

参考:https://github.com/6xiaoDi/blog-ECMScript-Series/tree/a3.95
Branch: branch02

commit description:a3.95(对象扩展:Object.fromEntries()——应用)

tag:a3.95


3. 字符串扩展:String.prototype.trimStart() ,String.prototype.trimEnd()

  • String.prototype.trimStart() => 去除字符串开头的空格

  • String.prototype.trimEnd() => 去除字符串末尾的空格


3.1 String.prototype.trimStart()

trimStart() 方法从字符串的开头删除空格,trimLeft()是此方法的别名。

注意:虽然 trimLefttrimStart的别名,但是你会发现 String.prototype.trimLeft.name === 'trimStart',一定要记住


3.2 String.prototype.trimEnd()

trimEnd()方法从一个字符串的右端移除空白字符,trimRighttrimEnd的别名。

注意

虽然 trimRighttrimEnd的别名,但是你会发现 String.prototype.trimRight.name === 'trimEnd',一定要记住


3.3 code

通过正则表达式去除字符串的首尾空格

\s => 是匹配所有空白符,包括换行。

replace => 返回一个新字符串

const str = '   abcde   '
// 正则
console.log(str)
console.log(str.replace(/^\s+/g, '')) // 去掉前面的空格
console.log(str.replace(/\s+$/g, '')) // 去掉后面的空格

image-20201129163007033

参考:https://github.com/6xiaoDi/blog-ECMScript-Series/tree/a3.96
Branch: branch02

commit description:a3.96(字符串扩展——通过正则表达式去除字符串的首尾空格)

tag:a3.96


console.log(str.replace(/^\s+/g, '').replace(/\s+$/g, ''))

参考:https://github.com/6xiaoDi/blog-ECMScript-Series/tree/a3.97
Branch: branch02

commit description:a3.97(字符串扩展——最终通过正则表达式去除字符串的首尾空格)

tag:a3.97


如下trim方法,均返回新的字符串。

const str = '   abcde   '
// 去掉前面的空格(两种写法)
console.log(str.trimStart())
console.log(str.trimLeft())
// 去掉后面的空格(两种写法)
console.log(str.trimEnd())
console.log(str.trimRight())
// 去除前后空格
console.log(str.trim())

image-20201129163638906

参考:https://github.com/6xiaoDi/blog-ECMScript-Series/tree/a3.98
Branch: branch02

commit description:a3.98(字符串扩展——String.prototype.trimStart() ,String.prototype.trimEnd()基本使用)

tag:a3.98


综上,如处理用户的表单提交,都会用到去除首尾空格的方法。


4. 数组扩展:Array.prototype.flat(),Array.prototype.flatMap()

  • Array.prototype.flat()
  • Array.prototype.flatMap()

=> 对于多维数组,进行扁平化操作。


4.1 Array.prototype.flat()

flat()方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。

const newArray = arr.flat(depth)

参数含义必选
depth指定要提取嵌套数组的结构深度,默认值为 1N

flat 默认只能拍平一级

存在一个参数:默认为1,表示扁平化的深度

flat(Infinity) => 完全扁平化,一般很少用,直接传深度即可。

const arr = [1, 2, 3, [4, 5, 6, [7, 8, 9, [10, 11, 12]]]]
console.log(arr.flat())
console.log(arr.flat().flat())
console.log(arr.flat().flat().flat())
console.log(arr.flat(3))
console.log(arr.flat(Infinity))

image-20201129171413448

参考:https://github.com/6xiaoDi/blog-ECMScript-Series/tree/a3.99
Branch: branch02

commit description:a3.99(数组扩展——Array.prototype.flat()基本使用)

tag:a3.99


4.2 Array.prototype.flatMap()

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

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

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

数组循环遍历输出可使用数组下的map方法,其参数是一个回调函数,可进行数组每一项的逻辑处理。

const arr = [1, 2, 3, 4, 5]
const res = arr.map(x => x + 1)
console.log(res)

image-20201129171727520

参考:https://github.com/6xiaoDi/blog-ECMScript-Series/tree/a4.01
Branch: branch02

commit description:a4.01(数组扩展——Array.prototype.map()基本使用)

tag:a4.01


利用map生成的二维数组,可以进行扁平化操作,直接用flat即可。

但是es10提供了flatMap,相当于flatmap的结合体,即遍历和扁平化同时进行。

const arr = [1, 2, 3, 4, 5]
const res = arr.map(x => [x + 1])
console.log(res)
const res = arr.map(x => [x + 1]).flat()
console.log(res)
const res = arr.flatMap(x => [x + 1])
console.log(res)

image-20201129172236693

参考:https://github.com/6xiaoDi/blog-ECMScript-Series/tree/a4.02
Branch: branch02

commit description:a4.02(数组扩展——Array.prototype.flatMap()基本使用)

tag:a4.02


注意:Array.prototype.flatMap()只能扁平化一层,并且没有深度参数。这点需要与flat区分开来。

const arr = [1, 2, 3, 4, 5]
const res1 = arr.map(x => [x + 1])
console.log(res1)
const res2 = arr.map(x => [x + 1]).flat()
console.log(res2)
const res3 = arr.flatMap(x => [[x + 1]])
console.log(res3)

image-20201129172611691

参考:https://github.com/6xiaoDi/blog-ECMScript-Series/tree/a4.03
Branch: branch02

commit description:a4.03(数组扩展——Array.prototype.flatMap()只能扁平化一层,并且没有深度参数。)

tag:a4.03


对比下 mapflatMap的区别

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

5. 修订Function.prototype.toString()

  • 返回源代码的实际文本片段

函数是对象,并且每个对象都有一个.toString() 方法,因为它最初存在于Object.prototype.toString()上。所有对象(包括函数)都是通过基于原型的类继承从它继承的。这意味着我们以前已经有funcion.toString() 方法了。

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

这意味着还将返回注释、空格和语法详细信息。

即对象上有toString方法,而函数又属于对象,因此function也具有toString方法。

// toString()
function foo(){
    // 这是es10
    console.log('abcde')
}
console.log(foo.toString())

整个函数及注释、空格、换行等都被文本化了。(es10之前只返回函数名称)

image-20201129222336036

参考:https://github.com/6xiaoDi/blog-ECMScript-Series/tree/a4.04
Branch: branch02

commit description:a4.04(修订Function.prototype.toString())

tag:a4.04


6. 可选的Catch Binding

  • 省略catch绑定的参数和括号

es10之前的语法当中,catch后参数是必须要写的,现在不需要的话参数和括号都可以说省略。

ES10之前我们都是这样捕获异常的:

try {
    // tryCode
} catch (err) {
    // catchCode
}

在这里 err是必须的参数,在 ES10可以省略这个参数:

try {
    console.log('Foobar')
} catch {
    console.error('Bar')
}

如之前的代码 =>

这里我故意把json的字符串格式写错。

const validJSON = json => {
    try {
        JSON.parse(json)
    } catch(e) {
        console.log(e)
    }
}

const json = '{name":"QH", "course": "es"}'
console.log(validJSON(json))

报错:当前并不是一个可解析的JSON格式的字符串。

image-20201130003500643

参考:https://github.com/6xiaoDi/blog-ECMScript-Series/tree/a4.05
Branch: branch02

commit description:a4.05(可选的Catch Binding——过去的捕获写法)

tag:a4.05


es10中不关注错误信息。 =>

const validJSON = json => {
    try {
        JSON.parse(json)
        return true
    } catch {
        return false
    }
}

const json = '{name":"QH", "course": "es"}'
console.log(validJSON(json))

false

参考:https://github.com/6xiaoDi/blog-ECMScript-Series/tree/a4.06
Branch: branch02

commit description:a4.06(可选的Catch Binding——传递错误)

tag:a4.06


6.1 应用:验证参数是否为json格式

这个需求我们只需要返回truefalse,并不关心catch的参数。

const validJSON = json => {
    try {
        JSON.parse(json)
        return true
    } catch {
        return false
    }
}

const json = '{"name":"QH", "course": "es"}'
console.log(validJSON(json))

true

参考:https://github.com/6xiaoDi/blog-ECMScript-Series/tree/a4.07
Branch: branch02

commit description:a4.07(可选的Catch Binding——传递正确)

tag:a4.07


7. JSON扩展:JSON superset,JSON.stringify()增强能力

  • JSON superset => JSON超集 \u2029 \u2028
  • JSON.stringify()增强能力

7.1 JSON superset(超集)

什么是 JSON超集?

简而言之就是让 ECMAScript兼容所有JSON支持的文本。 ECMAScript曾在标准 JSON.parse部分阐明 JSON确为其一个子集,但由于 JSON内容可以正常包含U+2028行分隔符 与U+2029段分隔符,而ECMAScript 却不行。


es10实际想让es完全兼容JSON文本,在早期的版本中仅仅规定JSON只是es的一个子集。JSON实际是可以正常显示行分隔符和段分隔符的,但是es却不行。es10则是做了升级,让es识别行分隔符和段分隔符。

行分隔符 => \u2028

段分隔符 => \u2029

以下引入段分隔符,es也不会报错了。

// JSON 超集 \u2029 \u2028
eval('var str="abcdef";\u2029 function foo(){return str;}')
console.log(foo())

abcdef

参考:https://github.com/6xiaoDi/blog-ECMScript-Series/tree/a4.08
Branch: branch02

commit description:a4.08(JSON扩展——JSON superset)

tag:a4.08


7.2 JSON.stringify() 增强能力

之前JSON.stringify()的解析是有范围的 => 0xD800~0xDfff,如果超出这个范围,显示就会存在问题(bug)。

es10补充了JSON.stringify()的解析显示范围。

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

console.log(JSON.stringify('\uD83D\uDE0E')) // emoji
console.log(JSON.stringify('\uD83D'))

emoji表情。它是多字节的一个字符,如果只输出其中的一部分,这一部分是无效的字符串,es10会将其直接解析成字符串,原样输出es10之前会将其转化为特殊字符,这是错误的。

image-20201130103658490

参考:https://github.com/6xiaoDi/blog-ECMScript-Series/tree/a4.09
Branch: branch02

commit description:a4.09(JSON扩展——JSON.stringify()增强能力)

tag:a4.09


8. Symbol扩展:Symbol.prototype.description

Symbol类型是es6新增,一般表示对象属性的唯一性,才使用它。

Symbol中通常传递一个参数,表示Symbol的描述。

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

const name = Symbol('es')
console.log(name.toString()) // Symbol(es)
console.log(name) // Symbol(es)
console.log(name === 'Symbol(es)') // false
console.log(name.toString() === 'Symbol(es)') // true

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

// Symbol
const s = Symbol('ABCDEF')
console.log(s)
console.log(s.description) // es10新增只读属性

image-20201130105541653

参考:https://github.com/6xiaoDi/blog-ECMScript-Series/tree/a4.10
Branch: branch02

commit description:a4.10(Symbol扩展——Symbol.prototype.description)

tag:a4.10


description是可读属性,不可修改。

如果不传参,默认描述信息就是undefined

// Symbol
const s = Symbol('ABCDEF')
console.log(s)
console.log(s.description) // es10新增只读属性

s.description = 'es'
console.log(s)

const s2 = Symbol()
console.log(s2.description) // undefined

image-20201130111704436

image-20201130111806883

参考:https://github.com/6xiaoDi/blog-ECMScript-Series/tree/a4.11
Branch: branch02

commit description:a4.11(Symbol扩展——Symbol.prototype.description特征)

tag:a4.11




(后续待补充)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值