当前位置:网站首页>Es2019 key summary
Es2019 key summary
2022-06-30 04:10:00 【Runqing】
1.Array.prototype.flat()
Array.prototype.flat() Used to nest arrays “ Flatten ”, Into a one-dimensional array . This method returns a new array , No impact on the original data .flat(depth),flat() By default, only “ Flatten ” First floor , If you want to “ Flatten ” Multiple nested arrays , Can be flat() The parameter of the method is written as an integer , Indicates the number of layers you want to flatten ,depth The default is 1.
const arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]
const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]
const arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]
// If no matter how many layers are nested , It's all going to be a one-dimensional array , It can be used Infinity Keywords as parameters .
const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// If the original array has spaces ,flat() Method will skip the empty space .
[1, 2, , 4, 5].flat()
// [1, 2, 4, 5]
2.Array.prototype.flatMap()
flatMap() Method first uses the mapping function to map each element , Then compress the result into a new array .
It is associated with map The connection depth value is 1 Of flat Almost the same , but flatMap It's usually a little more efficient to merge into one method .
[1, 2, 3, 4].flatMap((x) => [x * 2])
// [2, 4, 6, 8]
// It's equivalent to first map Again flat()
[1, 2, 3, 4].map(x => [x * 2]).flat()
// [2, 4, 6, 8]
3.String.prototype.trimStart()
trimStart() Method to remove spaces from the beginning of a string ,trimLeft() Is an alias for this method .
Returns a new string , To begin with ( Left side ) Call string with spaces removed .
var str = " foo ";
console.log(str.length); // 8
str = str.trimStart() // Equate to str = str.trimLeft();
console.log(str.length); // 5
console.log(str); // "foo "
4.String.prototype.trimEnd()
trimEnd() Method to remove white space from the end of a string .trimRight() It's another name for this method .
Returns a new string , Represents the end of the slave call string ( Right ) End Remove Blank .
var str = " foo ";
console.log(str.length); // 8
str = str.trimRight(); // Or written as str = str.trimEnd();
console.log(str.length); // 6
console.log(str); // ' foo'
5.String.prototype.matchAll()
matchAll() Method returns an iterator containing the results of all matching regular expressions and the group capture group .
stay matchAll Before appearance , By calling in the loop regexp.exec() or string.match() To get all the match information ( among regexp Must use /g sign )
before
// Method 1
function collectGroup1 (regExp, str) {
const matches = []
while (true) {
const match = regExp.exec(str)
// among regexp Must use /g sign , Otherwise, start from the first place every time , It's easy to fall into a dead cycle
if (match === null) break
// Add capture of group 1 to `matches`
matches.push(match[1])
}
return matches
}
collectGroup2(/"([^"]*)"/g, `"foo" and "bar" and "baz"`)
// [ 'foo', 'bar', 'baz' ]
// Method 2
// str.replace() In addition to supporting strings, it also supports functions
function collectGroup1 (regExp, str) {
const matches = []
function replacementFunc (all, first) {
matches.push(first)
}
str.replace(regExp, replacementFunc)
return matches
}
collectGroup2(/"([^"]*)"/ug, `"foo" and "bar" and "baz"`)
// ["foo", "bar", "baz"]
// without flag /g, .exec() Just return the first match
let re = /[abc]/
re.exec('abc')
// ["a", index: 0, input: "abc", groups: undefined]
re.exec('abc')
// ["a", index: 0, input: "abc", groups: undefined]
after
With matchAll after
function collectGroup3 (regExp, str) {
let results = []
for (const match of str.matchAll(regExp)) {
results.push(match[1])
}
return results
}
collectGroup3(/"([^"]*)"/g, `"foo" and "bar" and "baz"`)
// ["foo", "bar", "baz"]
6.Object.fromEntries()
Object.fromEntries() Method to convert the list of key value pairs to an object .
// example 1:
Object.fromEntries([['foo', 1], ['bar', 2]])
// {foo: 1, bar: 2}
// example 2
const entries = new Map([
['foo', 'bar'],
['baz', 42]
]);
const obj = Object.fromEntries(entries);
console.log(obj);
// { foo: "bar", baz: 42 }
A more common use case is with Entries Matching :
First use Object.entries Turn an object into an array , After using the array method to process the data , Reuse Object.fromEntries Convert to object .
// Only keep the attribute name in the object with a length equal to 3 Part of , And change its attribute value to the original 2 times
let obj = {
abc: 1, def: 2, ghij: 3 }
let res = Object.fromEntries(
Object.entries(obj)
.filter(([ key, val ]) => key.length === 3)
.map(([ key, val ]) => [ key, val * 2 ])
)
console.log(res)
// res is { 'abc': 2, 'def': 4 }
7.Symbol.prototype.description
description Is a read-only property , It will be returned Symbol The string of the optional description of the object .
const name = Symbol('My name is axuebin')
console.log(name.description) // My name is axuebin
console.log(Symbol('desc').description);
// "desc"
console.log(Symbol.iterator.description);
// "Symbol.iterator"
8.Function.prototype.toString()
toString() Method returns a string representing the source code of the current function
function sum(a, b) {
return a + b;
}
console.log(sum.toString());
// "function sum(a, b) {
// return a + b;
// }"
9.try…catch
ES2019 after , Omission catch Of err Parameters
// before
try {
// ...
} catch (err) {
// ...
}
// after: Now you can omit err This parameter
try {
// ...
} catch {
// ...
}
10.BigInt
ES2019 Added a data type :BigInt, Used to handle more than 2^53 - 1 The number of . This was originally Javascript Can be used in the Number The maximum number represented .BigInt It can represent any large integer .
Add... After an entire number n The way to define a BigInt , Such as :10n, Or call function BigInt().
const theBiggestInt = 9007199254740991n;
// 9007199254740991n
const alsoHuge = BigInt(9007199254740991);
// 9007199254740991n
const hugeString = BigInt("9007199254740991");
// 9007199254740991n
const hugeHex = BigInt("0x1fffffffffffff");
// 9007199254740991n
const hugeBin = BigInt("0b11111111111111111111111111111111111111111111111111111");
// 9007199254740991n
Be careful :
Cannot be used for Math Methods in objects ;
Not with anything Number Instance mix operation , Both must be converted to the same type .
BigInt And ordinary integers are two values , They are not equal .
// BigInt and Number Not strictly equal , But loose is equal to .
42n === 42 // false
42n == 42 // true
And be careful when converting the two types back and forth , because BigInt Variables are converting to Number Variable may lose precision .
BigInt(123) // 123n
BigInt('123') // 123n
BigInt(false) // 0n
BigInt(true) // 1n
Boolean(0n) // false
Boolean(1n) // true
Number(1n) // 1
String(1n) // "1"
!0n // true
!1n // false
Use typeof When testing , BigInt Object returns “bigint” :
typeof 1n === 'bigint'; // true
typeof BigInt('1') === 'bigint'; // true
To any BigInt Value usage JSON.stringify() Will trigger TypeError, Because by default BigInt The value will not be in the JSON Serialization in . however , if necessary , You can customize the implementation BigInt.prototype.toJSON Method .
边栏推荐
- Pig-Latin (UVA492)
- 你清楚AI、数据库与计算机体系
- (03). Net Maui actual combat basic control
- [note] Introduction to data analysis on June 7, 2022
- After the win10 system uses the browser to download, the content is moved or deleted without reason
- Sql语句遇到的错误,求解
- The jupyter notebook kernel hangs up frequently and needs to be restarted
- 接口测试--如何分析一个接口?
- I spent three years in a big factory outsourcing, which subverted my understanding!
- A solution to the problem of "couldn't open file /mnt/repodata/repomd.xml"
猜你喜欢

An error occurs when sqlyog imports the database. Please help solve it!

Technology sharing | broadcast function design in integrated dispatching

《机器人SLAM导航核心技术与实战》第1季:第0章_SLAM发展综述

尝试链接数据库时出现链接超时报错,如何解决?

Day 11 script and game AI

(04). Net Maui actual MVVM

Implementation of aut, a self-developed transport layer protocol for sound network -- dev for dev column

Jour 9 Gestion des scripts et des ressources

AI落地的新范式,就“藏”在下一场软件基础设施的重大升级里

You know AI, database and computer system
随机推荐
【论文阅读|深读】DANE:Deep Attributed Network Embedding
el-upload上傳文件(手動上傳,自動上傳,上傳進度)
Blue Bridge Cup: magic cube rotation [Vocational group]
Semantic segmentation resources
数据链路层详解
Grasp grpc communication framework in simple terms
Splicing strings with custom functions
oslo_ config. cfg. ConfigFileParseError: Failed to parse /etc/glance/glance-api. Conf: a solution to errors
thinkphp5实现导入功能
Error Nova missingauthplugin: an auth plugin is required to determine endpoint URL
Day 9 script and resource management
El upload upload file (manual upload, automatic upload, upload progress)
Idea grey screen problem
[Thesis reading | deep reading] dane:deep attributed network embedding
How to solve the problem of link hyperlinks when trying to link the database?
Magical Union
Errno and PERROR
管道实现进程间通信之命名管道
AI落地的新范式,就“藏”在下一场软件基础设施的重大升级里
学校实训要做一个注册页面,要打开数据库把注册页面输入的内容存进数据库但是