JSON
对 JSON.stringify()
语法增强
JSON.stringify()
在 ES10 之前有一个 BUG:0xD800-0xDFFF
的unicode
显示错误(无法编码为UTF-8
)- ES10 进行修正:这部分字符以
\\u
转译编码的形式存在,可以正常显示
JSON.stringify('\u{D800}')
// '\ud880'
Array
- 扁平化:
Array.prototype.flat(depth: number): Array
const arr = [1, [2, 3], [4, 5, [6, 7]]]
// 扁平化:以规定的深度递归数组
// 深度默认为 1
Array.prototype.flatMap(depth: number): Array
const arr = [1, 2, 3]
// flatMap: flat + map
arr.flatMap(item => [item * 2]) // [1, 2, 3]
// 相当于
// arr.map(item => [item * 2]).flat()
String
String.prototype.trimXx(): string
const str = ' foo '
const s1 = str.trimLeft() // 别名: trimStart
// 相当于
// str.replace(/^\s+/g, '')
console.log(s1) // 'foo '
const s2 = str.trimRight() // 别名: trimEnd
// 相当于
// str.replace(/\s+$/g, '')
console.log(s2) // ' foo'
const s3 = str.trim()
// 相当于
// str.replace(/^\s+|\s+$/g, '')
console.log(s3) // 'foo'
console.log(str) // ' foo '
// 以上操作都不改变原字符串
String.prototype.matchAll(regExp): RegExpStringIterator
const str = `"foo" and "bar" and "baz"`
// 如何提取 foo、bar、baz?
// before
function select(regExp, str) {
const matches = []
while (true) {
const match = regExp.exec(str)
if (match === null) break
matches.push(match[1])
}
return matches
}
select(/"([^"]*)"/g, str) // ["foo", "bar", "baz"]
// 或
str.match(/"([^"]*)"/g) // [""foo"", ""bar"", ""baz""]
// 或
function select(regExp, str) {
const matches = []
str.replace(regExp, (all, first) => {
matches.push(first)
})
return matches
}
select(/"([^"]*)"/g, str) // ["foo", "bar", "baz"]
// --------------------------
// after
function select(regExp, str) {
const matches = []
for (const match of str.matchAll(regExp)) {
matches.push(match[1])
}
return matches
}
select(/"([^"]*)"/g, str) // ["foo", "bar", "baz"]
// str.matchAll(/"([^"]*)"/g) // RegExpStringIterator {}
Object
const arr = [['foo', 1], ['bar', 2]]
const obj = Object.fromEntries(arr)
console.log(obj) // { foo: 1, bar: 2 }
// 反向操作
const obj = { foo: 1, bar: 2 }
const arr = Object.entries(obj)
console.log(arr) // [['foo', 1], ['bar', 2]]
// 应用场景:Array 的 API 多于 Object,转换后可以调用 Array 的 API
try…catch
// before
try {} catch (e) {}
// after
try {} catch {}
// (e) 可以省略,ES10 之前不可以
BigInt
number
类型不能处理大于2^53
的数- ES10 新增的
BigInt
可以处理任意大的整数
const a = 11n
const b = 11
typeof a // bigint
typeof b // number
11n + 22n // 33n