当前位置:网站首页>Es2018 key summary
Es2018 key summary
2022-06-30 04:10:00 【Runqing】
1.for await of
(1)for await of and for…of Comparison and use of
for…of The loop is used to traverse the synchronized Iterator Interface ,for await…of Loops are used to traverse asynchronous Iterator Interface .
function Gen (time) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve(time)
}, time)
})
}
// for ... of
async function test1 () {
let arr = [Gen(2000), Gen(100), Gen(3000)]
for (let item of arr) {
console.log(Date.now(), await item.then(console.log))
}
}
test1()
// 2000
// 1616227047645 undefined
// 100
// 1616227049650 undefined
// 3000
// 1616227049651 undefined
// for await of
async function test () {
let arr = [Gen(2000), Gen(100), Gen(3000)]
for await (let item of arr) {
console.log(Date.now(), item)
}
}
test()
// 1616225851505 2000
// 1616225851506 100
// 1616225852505 3000
(2) Data structure custom asynchronous traversal
The custom asynchronous traversal is actually the same as Custom synchronization traversal There are many similarities :
Asynchronous iterative protocol
If you make an object traversable , It is necessary to comply with the asynchronous and iterative protocol , Requirements of the agreement
1. Object to deploy a Symbol.asyncIterator by key The key/value pair
( Synchronization achieves Symbol.iterator)
2. value Is a parameterless function that complies with the iterator protocol
iterator protocol
The iterator protocol requires the following conditions :
1. An object must contain a parameterless function next
2.next The return value is also an object , contain done and value attribute .
among done Indicates whether the traversal ends ,value Returns the value of the current traversal .
2.Promise.prototype.finally()
finally() Method is used to specify whether Promise What is the final state of the object , The execution of the then or catch After the specified callback function , Will perform the operation . It is often used to close the database connection .
finally Method does not take any arguments ,finally Operation in method , It should be state independent , Don't depend on Promise The results of the implementation of .
promise
.then(result => {
···})
.catch(error => {
···})
.finally(() => {
···});
3. Object's extension operator …
(1) Deconstruct assignment
Deconstruction assignment is used to take values from an object , It is equivalent to all traversable objects of the target object itself (enumerable)、 But properties that have not been read , Assign to the specified object .
let {
x, y, ...z } = {
x: 1, y: 2, a: 3, b: 4 };
x // 1
y // 2
z // { a: 3, b: 4 }
(2) Extension operator
Object's extension operator (…) Used to fetch all traversable properties of parameter object , Copy to current object .
const input = {
a: 1,
b: 2
}
const output = {
...input,
c: 3
}
console.log(output) // {a: 1, b: 2, c: 3}
4. Regular extensions
(1)s Modifier :dotAll Pattern
In regular expressions , spot (.) It's a special character , Represents any single character , But there are two exceptions .
One is four bytes UTF-16 character , This can be used u The modifier solves ;
The other is line terminator (line terminator character).
Line terminator , It is this character that represents the end of a line . The following four characters belong to “ Line terminator ”.
U+000A A newline (\n)
U+000D A carriage return (\r)
U+2028 Line separator (line separator)
U+2029 Segment separator (paragraph separator)
(1) character
s Modifier , bring . Can match any single character . This is known as dotAll Pattern , Immediate point (dot) For all characters .
foo.bar/.test('foo\nbar') // false
/foo.bar/s.test('foo\nbar') // true
(2) attribute
Regular expressions also introduce a dotAll attribute , Returns a Boolean value , Indicates whether the regular expression is in dotAll Pattern .
const re = /foo.bar/s;
re.test('foo\nbar') // true
re.dotAll // true
re.flags // 's'
(2) Named group matching named capture groups
// match
const str = '2021-03-20'
const reg = /(\d{4})-(\d{2})-(\d{2})/
console.log(str.match(reg))
// ["2021-03-20", "2021", "03", "20", index: 0, input: "2021-03-20", groups: undefined]
// index [ Start of matching results ]
// input [ Search string ]
// groups [ An array of capture groups or undefined( If no named capture group is defined )]
// exec
const matchObj = reg.exec(str);
const year = matchObj[1]; // 2021
const month = matchObj[2]; // 03
const day = matchObj[3]; // 20
// One problem with group matching is , The matching meaning of each group is not easy to see , And can only use numerical serial numbers
//( such as matchObj[1]) quote , If the order of groups changes , When quoting, you must modify the serial number .
// Named group matching (Named Capture Groups), Allows you to specify a name for each group match , It's easy to read code , It's easy to quote
const REG = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const matchObj = REG.exec('2021-03-20');
const year = matchObj.groups.year; // "2021"
const month = matchObj.groups.month; // "03"
const day = matchObj.groups.day; // "20"
// “ Named group matching ” Inside the parentheses , The head of the pattern adds “ question mark + Angle brackets + Group name ”
// ( Such as ?<year>), And then you can do it in exec Method returns the result groups Property to reference the group name .
// meanwhile , Number sequence number (matchObj[1]) Is still valid .
let t = '2021-03-20'.match(REG)
console.log(t.groups.year) // 2021
console.log(t.groups.month) // 03
console.log(t.groups.day) // 20
(3) The latter asserts that
stay ES2018 Before JavaScript Regular only supports antecedent assertions , Subsequent assertions are not supported .
(?<…) It's a sign of assertion ,(?..) Is the symbol of the first assertion and then combines =( be equal to )、!( Unequal )、\1( Capture match ).
Assert ahead & First negative assertion
“ Assert ahead ” refer to ,x Only in y The front matches , Must be written as /x(?=y)/
“ First negative assertion ” refer to ,x Only not in y The front matches , Must be written as /x(?!y)/.
let test = 'hello123helloworld'
// Assert ahead : matching hello, But it must be followed by 123
console.log(test.match(/hello(?=123)/))
// ["hello", index: 0, input: "hello123helloworld", groups: undefined]
// First negative assertion : matching hello, But the back must not be 123
console.log(test.match(/hello(?!123)/))
// ["hello", index: 8, input: "hello123helloworld", groups: undefined]
The latter asserts that & Later negative assertion
“ The latter asserts that ” Coincide with “ Assert ahead ” contrary ,x Only in y It's only after that , Must be written as /(?<=y)x/.
“ Later negative assertion ” Then with “ First negative assertion ” contrary ,x Only not in y It's only after that , Must be written as /(?<!y)x/.
let test = 'hello123helloworld'
// The latter asserts that : matching hello, But the front must be 123
console.log(test.match(/(?<=123)hello/))
// ["hello", index: 8, input: "hello123helloworld", groups: undefined]
// Later negative assertion : matching hello, But the front must not be 123
console.log(test.match(/(?<!123)hello/))
// ["hello", index: 0, input: "hello123helloworld", groups: undefined]
(4)Unicode Attribute class
Unicode Attribute class \p{key=value} To specify the attribute name and attribute value , This allows regular expressions to match a class of character groups .( For some properties , You can write only the attribute name , Or just write the attribute value .)
according to Unicode standard , every last Unicode Except that the character has a unique code point , There are other properties that are :Unicode Property、Unicode Block、Unicode Script.
\P{…} yes \p{…} Reverse matching of , That is, match characters that do not meet the conditions .
These two kinds are only for Unicode It works , So when you use it, you must add u Modifier . If not u Modifier , Regular expressions use \p and \P Will report a mistake .
for example :\p{Script=Greek} Specifies to match Greek letters or Match all numbers
// Match Greek letters
const regexGreekSymbol = /\p{Script=Greek}/u;
regexGreekSymbol.test('π') // true
// Match all numbers
const regex = /^\p{Number}+$/u;
regex.test('²³¹¼½¾') // true
regex.test('㉛㉜㉝') // true
regex.test('ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ') // true
Character encoding includes ASCII and Unicode, The document code includes UTF-8、GBK etc. .
File encoding has nothing to do with character encoding , Even if the file code is specified , Character changes can also be flexibly selected without any restrictions .
Unicode Property
Classify characters according to their functions , A character can only belong to one Unicode Property.
Can be Unicode property It is understood as a character group , In regular use /p{ Attribute types } Express .
for example p The character group and P Property , Lower case p Put it in capital letters , It is the exclusive character group of this character group .
think about it \d matching 0-9 This character group , and \D matching 0-9 Other character groups .
let input = 'abcdAeCd China '
console.log(input.match(/\p{L}/ug))
// ["a", "b", "c", "d", "A", "e", "C", "d", " in ", " countries "]
// The meaning of this code is to match all the characters in the input ( Unlimited language )
// What we use here is Unicode Property:{L}
// The meaning of this property is any letter in any language . It's sort of equivalent to :
let input = 'abcdAeCd China '
console.log(input.match(/./sg))
// ["a", "b", "c", "d", "A", "e", "C", "d", " in ", " countries "]
// Other types :
// {Ll} [ Any lowercase letter with a capital letter ]
// {N} [ Numbers in any language ]
Unicode Script
Divide characters according to the writing system they belong to , It usually corresponds to a certain language . such as \p{Script=Greek} It means Greek ,\p{Script=Han} It means Chinese .
All we need to do is Unicode Scripts Find the corresponding name , You don't need to calculate all the characters of the corresponding language Unicode Range .
before:
let input = `I'm chinese! I'm Chinese `
console.log(input.match(/[\u4e00-\u9fa5]+/))
// [" I'm Chinese ", index: 12, input: "I'm chinese! I'm Chinese ", groups: undefined]
after:
let input = `I'm chinese! I'm Chinese `
console.log(input.match(/\p{Script=Han}+/u))
// [" I'm Chinese ", index: 12, input: "I'm chinese! I'm Chinese ", groups: undefined]
Unicode Block
take Unicode Characters are divided according to the coding interval , So every character belongs to only one Unicode Block, Illustrate with examples :
\p{InBasic_Latin}: U+0000–U+007F
\p{InLatin-1_Supplement}: U+0080–U+00FF
\p{InLatin_Extended-A}: U+0100–U+017F
\p{InLatin_Extended-B}: U+0180–U+024F
边栏推荐
- 深入浅出掌握grpc通信框架
- (04). Net Maui actual MVVM
- Grasp grpc communication framework in simple terms
- If you encounter problems when using spark for the first time, please ask for help
- Day 11 script and game AI
- 你清楚AI、数据库与计算机体系
- Daily summary of code knowledge
- Find the interface and add parameters to the form
- Titanic(POJ2361)
- base64.c
猜你喜欢

Day 11 script and game AI

Postman learning sharing

【云原生】AI云开发平台——AI Model Foundry介绍(开发者可免费体验AI训练模型)

学校实训要做一个注册页面,要打开数据库把注册页面输入的内容存进数据库但是
![[summary of skimming questions] database questions are summarized by knowledge points (continuous update / simple and medium questions have been completed)](/img/89/fc02ce355c99031623175c9f351790.jpg)
[summary of skimming questions] database questions are summarized by knowledge points (continuous update / simple and medium questions have been completed)

Green new power and "zero" burden of computing power -- JASMINER X4 series is popular

The school training needs to make a registration page. It needs to open the database and save the contents entered on the registration page into the database

关于智能视觉组上的机械臂

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

【模糊神经网络预测】基于模糊神经网络实现水质预测含Matlab源码
随机推荐
EasyCVR部署服务器集群时,出现一台在线一台不在线是什么原因?
Implementation of aut, a self-developed transport layer protocol for sound network -- dev for dev column
Pig-Latin (UVA492)
Node red series (28): communication with Siemens PLC based on OPC UA node
Clients accessing the daytime service (TCP)
2021-11-04
Interpretation score of bilstm-crf in NER_ sentence
thinkphp5实现导入功能
Analysis of similarities and differences of various merged features (Union, merge, append, resolve) in ArcGIS
Maya Calendar(POJ1008)
2021-07-14
(04).NET MAUI实战 MVVM
基于海康EhomeDemo工具排查公网部署出现的视频播放异常问题
win10系统使用浏览器下载后,内容无故移动或删除
Knowledge - how to build rapport in sales with 3 simple skills
RPC correction based on arcpy API
Thinkphp5 implements import function
[Thesis reading | deep reading] dane:deep attributed network embedding
如何利用FME 创建自己的功能软件
I get n offers in two months. I don't have any difficult interviewers here