当前位置:网站首页>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 .
边栏推荐
- (04).NET MAUI实战 MVVM
- Unity 在編輯器中輸入字符串時,轉義字符的輸入
- EasyCVR部署服务器集群时,出现一台在线一台不在线是什么原因?
- Hebb and delta learning rules
- [note] on May 27, 2022, MySQL is operated through pychart
- Node red series (28): communication with Siemens PLC based on OPC UA node
- Green new power and "zero" burden of computing power -- JASMINER X4 series is popular
- errno和perror
- el-upload上傳文件(手動上傳,自動上傳,上傳進度)
- 【论文阅读|深读】Role2Vec:Role-Based Graph Embeddings
猜你喜欢

【论文阅读|深读】DANE:Deep Attributed Network Embedding

Educoder group purchase suspension box page production

Geometric objects in shapely

Cloud native -- websocket of Web real-time communication technology

el-upload上传文件(手动上传,自动上传,上传进度)

lego_loam 代码阅读与总结

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

Radiant energy, irradiance and radiance

Jour 9 Gestion des scripts et des ressources

如何通过进程启动来分析和解决EasyCVR内核端口报错问题?
随机推荐
base64.c
SQL追加字段
Quick sort & merge sort
DO280私有仓库持久存储与章节实验
Grasp grpc communication framework in simple terms
Daily summary of code knowledge
[operation] getting started with MySQL on May 23, 2022
找到接口在表单里加参数
[summary of skimming questions] database questions are summarized by knowledge points (continuous update / simple and medium questions have been completed)
节点CODE相同会导致数据重复
Pytorch Profiler+ Tensorboard + VS Code
Collinearity problem
RPC correction based on arcpy API
Errno and PERROR
Do280 private warehouse persistent storage and chapter experiment
第十二天 进阶编程技术
Solutions for project paths
How to analyze and solve the problem of easycvr kernel port error through process startup?
Use ideal to connect to the database. The results show some warnings. How to deal with this part
Unity 在编辑器中输入字符串时,转义字符的输入