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、array | Y |
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?