当前位置:网站首页>New usage and deconstruction assignment of data types
New usage and deconstruction assignment of data types
2022-07-18 06:18:00 【zzzlln】
Deconstruct assignment
(1)、 What is deconstruction assignment
ES6 Allow to follow certain mode , Extract values from arrays and objects , Assign values to variables , This is called deconstruction assignment (Destructuring).
About assigning values to variables , The traditional variable assignment is like this :

Set the element value of the array 1,2,3 Assign values to variables a,b,c, The result is as we wish , Assignment successful , This is a traditional way of assignment .
Deconstruction and assignment of variables :

Have you noticed ? The code of assignment is greatly reduced , There is no need to separate variables a,b,c Declare definition and assignment respectively , Just add variables a,b,c As an element of an array , And then the array [1,2,3] Assign to array [a,b,c] that will do , Variable a,b,c The corresponding values can be obtained respectively .
(2)、 Deconstruction and assignment of arrays
Deconstruction assignments can be nested

As we expected , Even if another array is nested in the array , Deconstruction assignment can also accurately assign values to our variables ,c1 and c2 The values of are 3.1 , 3.2, That is, the assignment is successful .
Incomplete deconstruction

When the pattern on the left ( You can understand it as format ) When it's not exactly the same as the right , So during the assignment process , Only the variables of the part with successful pattern matching will be assigned , for example : Variable c No matching pattern found on the right , Therefore, the assignment cannot be made , But it doesn't affect the variables a And variables b Assignment , Because they find a matching pattern on the right , This is called incomplete deconstruction .
Assignment unsuccessful , The value of the variable is undefined

Let's continue with the above example of incomplete deconstruction , Variable a And variables b For incomplete deconstruction , So variable c What will happen if the deconstruction fails ? remember , Deconstruction failed , The value of the variable is equal to undefined. It is equivalent to declaring only variables c, But no assignment .
Allow setting default values

Variables in the example c The default value has been specified as 3, It doesn't matter even if there is no corresponding value assigned to it on the right , It can be successfully assigned to 3, If you want to override the default 3, Just assign a valid value . as follows :

The default value at this time 3 Will be replaced by the new value 4 Cover ,c The value of is 4; Be careful : When the new value is undefined When , The default values will not be overwritten .
Demo sample : Structure assignment of array
(3)、 Object's deconstruction assignment
The deconstruction assignment of an object is very similar to that of an array , Let's look at a small piece of code :

Is the code of this example very similar to the deconstruction and assignment of arrays , It's just that arrays are replaced by objects . But there is one difference between the two , We make some modifications to the above code :

I put the object attribute on the right b And attribute c The position of the has been changed , But this does not affect the result of the assignment , Variable b And variables c The value of , Is still b by 2,c by 3. This tells us that the deconstruction and assignment of objects will not be affected by the order of attributes ( Arrays will be affected ), It is associated with the property name , The variable name should be consistent with the attribute name , Will succeed in assignment .
If the variable cannot find an attribute with the same name , The assignment will not succeed , Like the following example :

Variable a No attribute matching its name can be found on the right a, So the variable a Assignment unsuccessful ,a The value of is undefined.
But there is no way to remedy it , If you want to deconstruct and assign a value to a variable whose variable name is different from the attribute name , It can be written like this :

Variable a No attribute matching its name can be found on the right a, So the variable a Assignment unsuccessful ,a The value of is undefined.
But there is no way to remedy it , If you want to deconstruct and assign a value to a variable whose variable name is different from the attribute name , It can be written like this :

This variable a It can also be assigned successfully ,a The final value of is 2.
The usage of object deconstruction assignment is also very similar to array deconstruction assignment :
Object deconstruction assignment can also be nested

Default values can be specified

(4)、 Deconstruction and assignment of strings
Except that objects and arrays can be deconstructed and assigned , Strings can also be played like this , Take a look at the following example :

This is because in the process of deconstruction assignment , The string is converted to an array like object . Variable a,b,c,d,e,f Are assigned corresponding values .
Demo sample : Structure assignment of string
(5)、 The purpose of deconstruction assignment
1. Exchange the values of variables
The most common traditional method is to introduce a third variable to store temporarily , as follows :

But with deconstruction assignment , It's much easier to exchange the values of two variables . Look at the code below :

A simple sentence of code can be successfully exchanged x,y Value .
2. Extract multiple values returned by the function
Function can only return one value , We can put multiple values in an array or object , Then the value is extracted quickly by deconstruction assignment .

take demo The operation result of the function is assigned to the variable through the structure name and age, Realize fast extraction of corresponding values .
3. Define function parameters

In this way , It is very convenient to extract JSON The desired parameters in the object , For example, in the case of , We just need to get :a,b,c, There is no need to turn off other parameters , such as :d Or more parameters .
4. The default value of the function parameter
The traditional way to realize the default value of parameters is , First judge whether the parameter is undefined, If it's the representative who didn't pass , You need to assign a value to it manually , Such as :

But with deconstruction assignment , Everything has become much simpler ! Look at the code below :

The above code shows us how to set the default value of function parameters by deconstruction assignment , Simple code can be achieved . When calling a function, no corresponding name Parameters , here name The default value will be used :“ Zhang San ”, Is it very simple and convenient .
The above introduces the methods of deconstruction assignment 4 Uses , Do you also feel the convenience it brings us , It greatly reduces the amount of our code , And the grammar is very clear , It increases the readability and expressiveness of the code .
Demo sample : Purpose of structure assignment
5、 String usage
(1)、 Template string
ES6 Template string... Is introduced in (Template Literal), Is a new way to create strings . Template Strings use backquotes (` `) Instead of using double quotation marks and single quotation marks in ordinary strings . Template strings can contain specific syntax (${expression}) Placeholder for . With this new feature , We can better control dynamic strings . This will bid farewell to the days of long string connections .
If we want to splice a paragraph : Take a chestnut : Hello everyone , I'm Yaya , I come from Henan , I this year 22 Year old , My hobby is werewolf killing .
const Person = {
name: " Asia ",
age: 22,
hometown: " Henan ",
hobby: " Werewolf killing "
}
const intro = " Hello everyone , I am a " + Person.name + ", I come from " + Person.hometown +
", I this year " + Person.age + " Year old , My hobby is " + Person.hobby + "."
console.log(intro)
But you will find it troublesome to write like this , One Chinese, one English , One double quotation mark and one plus sign +. When we use it es6 After the template string in , You will find a new continent !
const intro2 =
` Hello everyone , I am a ${Person.name}, I come from ${Person.hometown}, I this year ${Person.age} Year old , My hobby is ${Person.hobby}. `
console.log(intro2)
in addition {} You can write some expressions in , such as :
const intro3 =
` Hello everyone , I am a ${Person.name}, I come from ${Person.hometown}, I this year ${Person.age} Year old , My hobby is ${Person.hobby}, I'll be next year ${Person.age + 1} Year old , I am already ${Person.age > 18 ? ' adults ' : ' A minor '} 了 .`
console.log(intro3)
(2)、repeat function
repeat( ) function : Repeat the target string N Time , Returns a new string , Does not affect the target string .

repeat 3 After that, a new string is returned and assigned to name2,name1 Unaffected , therefore name1 The value of does not change .
(3)、includes function
includes( ) function : Judge whether the string contains the specified substring , return true Means containing and false Indicates that... Is not included . The second parameter is optional , Indicates where to start the search .

We can use the traditional method indexOf( ) Function to implement , If it contains the specified string ,indexOf( ) The function will determine the position where the substring first appears , It doesn't contain , Then return to -1. We return whether the value is -1 To determine whether the string contains the specified substring , however , We can use it now includes( ) Function instead of indexOf( ) function , Because its return value is more intuitive (true or false), Besides, we don't care where the substring appears .
Be careful , The last code above , The second parameter is 1, Says from the first 2 Characters “ End “ Begin your search , First character ” front “ The position is 0.
(4)、startsWith function
startsWith( ) function : Determines whether the specified substring appears at the beginning of the target string , The second parameter is optional , Indicates where to start the search .

If we judge whether a string begins with a substring , You can use it directly startsWith( ) Function , Again , The second parameter is 1 Says from the first 2 Start searching with two characters . To search from the first character , Parameter should be 0 Or is empty ( By default, search from the first character ).
(5)、endsWith function
endsWith( ) function : Determine whether the substring appears at the end of the target string , The second parameter is optional , For the former N Characters .

(6)、string.raw function
The last function to be explained is String.raw( ); Look at the function name raw It means unprocessed , Just like this function : Returns the original appearance of the string , Even if the string contains an escape character , It turns a blind eye , Direct output . for instance : without String.raw( ) Processed string :

\n Will be recognized as a newline , Achieve line feed effect , And pass by String.raw( ) The result of the same string of is :

\n Was identified as \ and n Two characters , Lose the effect of line feed , Direct output , This is it. String.raw( ) The function of . It is often used as a template string handler , That is, add a template string directly after it .
Demo sample : New string usage
6、 Array usage
(1)、Array.of function
Function function : Put a set of values , Convert to array .

Isn't that easy to understand , The number passed in is :1~5, Last pass Array.of Function processing , You get an array , And the content of the array is [1,2,3,4,5].
(2)、Array.from function
Function function : You can convert objects like arrays or traversable objects into real arrays .
What are array like objects ? The most common is to call getElementsByTagName The result of the method , It is the result of an array like ,getElementsByTagName The method must be familiar , Let's take a look :

See the code above , We call getElementsByTagName Method , Get the result and save it in the variable ele in , Then judge its type , Find variables ele It's not an array , It's an object Array, An array like object Object, Next we use Array.from( ) We're going to process it , And judge the type again .

At this time, the result of our operation is :true, That's what happened Array.from Function to process the returned result , It has become a real array .
Array.from One of the functions is to convert a string into an array . Look at the following case :

character string “hello” The returned result after conversion has become an array :["h", "e", "l", "l","o"].
(3)、find function
Function function : Find the first element in the array that meets the criteria .

See the code above ,find() The parameter of the function is an anonymous function , Each element of the array will enter the anonymous function execution , Until the result is true,find The function will return value Value :3. If all elements do not meet the conditions of anonymous functions ,find( ) The function will return undefind. Look at the following code case :

In the case above , There is no greater than... In the array 7 The elements of , therefore find The function will return :undefined.
(4)、findIndex function
Function function : Returns the position subscript of the first array member that meets the condition .

The result of the above code is :2, Because the array element is larger than 8 The element is 9, The element 9 The location of the is 2,( Array elements are from 0 Count up ). If all elements do not meet the conditions of anonymous functions ,findIndex( ) The function will return -1.
(5)、fill function
Function function : Use the specified value , Fill in the array .

after fill( ) Array processed by function arr Has become [4,4,4]; Just like the function name fill( fill ) equally . All elements are filled with numbers 4 了 . If I want to fill in only some elements, can I ? Tolerable ,fill( ) The function provides some parameters , Used to specify the start and end positions of the fill .
Or the above case , Let's make a little adjustment , Show me again :

In the code above 2 Parameters and 3 A parameter means : From the position 1 The element of begins to fill in numbers 4, Cut off to position 3 Before , So it's the location 1 And location 2 The elements of are numbered 4 Filled , The result :[1,4,4].
(6)、entries function
Function function : Traverse the key value pairs of the array , Returns a traverser , It can be used for..of Traverse it .
Traversers and for..of It's also ES6 New features , At present, we haven't introduced , We can have a simple cognition first .
Back to our entries( ) function , Look at a case :

In the above code , We will entries( ) Function returns an iterator , use for...of Traversal , And print out the results , You can get the key value of the array :0 and 1, And the corresponding array elements :‘a‘ and ’b‘.
If you only want to traverse the index key of the array , You can use another instance method .
(7)、keys function
Function function : Traverse the index key of the array , Returns a traverser .

Just like the above running results , We printed out the index key of the array :0 and 1.
If we want to traverse only the elements of the array , We can use two instance methods .
(8)、values function
effect : Iterate over the elements of an array , Returns a traverser .

The running result of the above code is also what we expected , Finally, the elements of the array are printed :a and b.
In addition to new functions ,ES6 It also brings a new concept to arrays : Array derivation .
边栏推荐
- Some notes on kubelet in kubernetes
- R语言使用lm函数构建线性回归模型、使用I运算符嵌入表达式、使用表达式指定回归方程的形式
- What if there is no sound when playing lol after reinstalling the system win11?
- let / const /var的区别
- Analysis of keepalive keeping alive mechanism of TCP protocol layer in IM development
- 2022安全员-C证特种作业证考试题库及答案
- 在线问题反馈模块实战(二):封装代码自动生成类文件器
- 杰理之内置触摸可供修改的参数【篇】
- Where can I find the computer network speed detection
- [MySQL learning notes 33] log
猜你喜欢
Dry goods semantic web, Web3.0, Web3, metauniverse, these concepts are still confused? (top)

迪文串口屏教程(2)

Do not know how to improve the visual language model? Zhejiang University and Lianhui Research Institute put forward a new multi-dimensional evaluation framework

函数高级应用

Practice of online problem feedback module (III): automatically generate all controller, service, mapper and other files
![[server data recovery] a data recovery case of RAID5 crash caused by hard disk offline during data synchronization of a hot spare disk of an IBM model](/img/58/fa55af5f13fca44bd754281d62a3a7.jpg)
[server data recovery] a data recovery case of RAID5 crash caused by hard disk offline during data synchronization of a hot spare disk of an IBM model

De la numérisation à l'exploitation et à la maintenance intelligentes: Quelles sont les valeurs et les défis?

ECCV 2022 | 多域长尾分布学习,不平衡域泛化问题研究(开源)

量子计算+半导体材料!Quantinuum和JSR达成合作

2、Deep Learning in Higher Dimensions
随机推荐
Xiamarin integrates braze to realize messaging and end-to-end notification
Network socket programming
阿里内网疯传的P8“顶级”分布式架构手册被我拿到了
华为通用卡证识别功能,一键实现多种卡绑定
Quantum computing + semiconductor materials! Quantum and JSR reach cooperation
let / const /var的区别
The third question of the 13th Landbridge cup 2022 - sum (prefix sum or formula method)
Web开发人员的10个数据库优化最佳实践
Neusoft Ruichi has reached a strategic cooperation with United electronics to seize a new outlet in the domestic basic software market
Sword finger offer punch array and matrix
线性代数 笔记2
ECCV 2022 | 多域长尾分布学习,不平衡域泛化问题研究(开源)
迪文串口屏教程(3)
【mysql学习笔记33】日志
Engineering monitoring vibrating wire wireless acquisition instrument external digital sensor access logic and data transmission
迪文串口屏教程(1)
What if there is no sound when playing lol after reinstalling the system win11?
Scan code login function of IM instant messaging software development
regular expression
QT ui设计师界面常用操作记录(QTableWidget)