当前位置:网站首页>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
边栏推荐
- Refers to the difference between IP and *ip at output
- .NET 7 的 JWT 配置太方便了!
- Day 12 advanced programming techniques
- 绿色新动力,算力“零”负担——JASMINER X4系列火爆热销中
- 接口测试--如何分析一个接口?
- EasyCVR部署服务器集群时,出现一台在线一台不在线是什么原因?
- [summary of skimming questions] database questions are summarized by knowledge points (continuous update / simple and medium questions have been completed)
- 尝试链接数据库时出现链接超时报错,如何解决?
- Robot slam navigation core technology and practice Season 1: Chapter 0_ Slam development overview
- Do280 private warehouse persistent storage and chapter experiment
猜你喜欢

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

(04).NET MAUI实战 MVVM
![[cloud native] AI cloud development platform - Introduction to AI model foundry (developers can experience AI training model for free)](/img/08/b390810d457af5e4470d9743b01ca1.png)
[cloud native] AI cloud development platform - Introduction to AI model foundry (developers can experience AI training model for free)

Simple theoretical derivation of SVM (notes)
![[image fusion] multi focus and multi spectral image fusion based on cross bilateral filter and weighted average with matlab code](/img/9c/2553d192c2f9b93acc6550220c447f.png)
[image fusion] multi focus and multi spectral image fusion based on cross bilateral filter and weighted average with matlab code

两个月拿到N个offer,什么难搞的面试官在我这里都不算事
![[Thesis reading | deep reading] role2vec:role based graph embeddings](/img/69/c94700fbbbda20df4e54803c703b48.png)
[Thesis reading | deep reading] role2vec:role based graph embeddings

How to solve the problem of link hyperlinks when trying to link the database?

毕业设计EMS办公管理系统(B/S结构)+J2EE+SQLserver8.0
![Blue Bridge Cup: magic cube rotation [Vocational group]](/img/ba/aeae2744f3aaa1052b5af452f990e2.jpg)
Blue Bridge Cup: magic cube rotation [Vocational group]
随机推荐
Default value of JS parameter
Day 11 script and game AI
Unity 在編輯器中輸入字符串時,轉義字符的輸入
【图像融合】基于交叉双边滤波器和加权平均实现多焦点和多光谱图像融合附matlab代码
oslo_ config. cfg. ConfigFileParseError: Failed to parse /etc/glance/glance-api. Conf: a solution to errors
毕业设计EMS办公管理系统(B/S结构)+J2EE+SQLserver8.0
Integrating viewbinding and viewholder with reflection
Use ideal to connect to the database. The results show some warnings. How to deal with this part
Analysis of similarities and differences of various merged features (Union, merge, append, resolve) in ArcGIS
matplotlib. pyplot. Hist parameter introduction
(04). Net Maui actual MVVM
thinkphp5实现导入功能
Unity 在编辑器中输入字符串时,转义字符的输入
ThingsBoard教程(二三):在规则链中计算二个设备的温度差
如何利用FME 创建自己的功能软件
Collinearity problem
[summary of skimming questions] database questions are summarized by knowledge points (continuous update / simple and medium questions have been completed)
[operation] MySQL query operation 2 on May 25, 2022
A solution to the problem of "couldn't open file /mnt/repodata/repomd.xml"
DBT product initial experience