Deconstruction: Make data access more convenient!

Preface

Original intention : Recently I was reading the book "In-depth Understanding of Es6" . I didn't fully learn Es6 grammar before. I also took advantage of the busy stage to re-study and sort out the notes to share with everyone. If you don't like it, don't spray.

Suitable for the crowd : front-end primary development, big guys detour.

Content structure : basic grammar -> grammar pros and cons -> application scenarios

Why use deconstruction

In Es5, we usually did this before we wanted to get specific data from an object or array object. Look at the following example

let person = {
    
    
    name: "蛙人",
    age: 24
}

let name = person.name
let age = person.age

In the above example, we can see that we personget the namesum ageattribute from the object and assign it to the newly declared variable namesum age. It is okay to declare two variables in this way, if there are more in the future.

Therefore, Es6 provides destructuring functions for objects and arrays, making the process of breaking up the data structure easier, and obtaining the required information from a smaller part after breaking up. Let's take a look

Object deconstruction

let person = {
    
    
    name: "蛙人",
    age: 24
}
let {
    
     name, age } = person
console.log(name) // 蛙人
console.log(age) // 24

In the above example, person.namethe value of is assigned to the namevariable, and person.agethe value of is assigned to the agevariable. It's just that the abbreviated syntax of objects is used here. If you don't understand the new features of objects, please see my last article "What features are extended by Es6 objects?"

Don't forget to initialize the value

If you use var, let, constused to declare deconstruction, it is necessary to initialize the value of the variable is right. Let's look at an example

var { name, age }; // 语法抛出错误
let { name, age }; // 语法抛出错误
const { name, age }; // 语法抛出错误

In the above example, we can see that there are declarations for destructuring assignment and not initializing the value, then an error will be thrown. If it is not used for destructuring, varand the letdeclared variable can not be initialized, but the constdeclared variable must be initialized, otherwise an error will be thrown. If you do not understand var, let, constdifferences, I see this "var, let, const between the three types one can understand."

Note: If the value on the right side of the destructuring assignment is nullor undefined, an error will be thrown, remember.

Destructuring assignment

In the above, we have finished deconstruction, so what is deconstruction assignment. That is, we also use destructuring syntax when assigning values ​​to variables. Look at the following example

let name = "小王"
let age = 18
let person = {
    name: "蛙人",
    age: 24
};
// 使用解构赋值为变量赋值
({ name, age } = person);
console.log(name) // 蛙人
console.log(age) // 24

In the above example, we first defined the namesum agevariable, initialized the value, and then read and re-assigned the namesum agevariable from the personobject by destructuring the assignment method . 注意,一定要用一对小括号包裹解构赋值语句, The JavaScriptengine will treat the curly braces as a code block, and the grammar stipulates that the code block cannot appear on the left side of the assignment statement. The code block can be converted into an expression after being wrapped in parentheses, so that destructuring assignment can be realized.

Next, we use destructuring assignment expressions in function parameters

let name = "小王"
let age = 18
let person = {
    
    
    name: "蛙人",
    age: 24
};
function getObj(data) {
    
    
    console.log(data == person) // true 这里的data就是person,表达式的值就是 =右侧的的值
}
getObj({
    
     name, age } = person)
console.log(name) // 蛙人
console.log(age) // 24

In the above example, getObja destructuring assignment expression is passed in when the function is called . Since JavaScriptthe value of the expression is the value on the right side, the parameter object in the function is the personobject, nameand the agevariable will also be reassigned.

When using destructuring assignment, if the specified variable name does not exist in the object, then this variable is undefined. Look at the following example

let person = {
    
    
    name: "蛙人",
    age: 24
}
let {
    
     name, age, sex} = person;
console.log(name, age, sex) // 蛙人 24 undefined

In the above example, there is a sexvariable in the destructuring assignment expression , but obviously this sexattribute does not exist in the object, then the sexvariable will be assigned to undefined.

When the specified attribute does not exist, we can set a default value, which is the same as the default value of the function parameter. Look at the following example

let person = {
    
    
    name: "蛙人",
    age: 24
}
let {
    
     name, age, sex = "male" } = person;
console.log(name, age, sex) // 蛙人 24 male

In the above example, the sexdefault value is set person. This default value will only take effect when there is no such property on the object or the property is undefined. This is the same as the default value of the function. If you don’t understand, you can read my article "You Do you really understand the function features in ES6? " .

Destructuring and assigning aliases

In the above code, our deconstructed expressions are all the same as the variable and the attribute name, so sometimes we deconstructed and don't want to be the same as the attribute name. What should we do? The deconstructed expression agrees to support aliases. Look at the following example

let person = {
    
    
    name: "蛙人",
    age: 24
}
let {
    
     name: userName, age: userAge } = person
console.log(userName) // 蛙人
console.log(userAge) // 24

In the above example, in the above expression deconstruction nameattributes are stored in the userName, the ageproperties are stored in a userAge, then the time can not be accessed nameand age, and as the men were not the variables.

Destructuring and assigning aliases also support default parameters

let person = {
    name: "蛙人",
    age: undefined
}
let { name: userName, age: userAge = 24 } = person
console.log(userName) // 蛙人
console.log(userAge) // 24

Not much to say here, it is the same as the default parameters mentioned above.

Object multi-level nesting deconstruction

Destructuring assignment also supports multi-level nesting, and the syntax is the same as the object literal mentioned above, and it can be deconstructed in more detail. Look at the following example

let person = {
    
    
    name: "蛙人",
    age: 24,
    hobby: {
    
    
    	name: "写代码"
    }
}
let {
    
     hobby: {
    
     name: code = "code" } } = person
console.log(code) // 写代码

In the above example, you can see that the above multi-layer deconstruction grammar is the same as ordinary deconstruction, except that one layer of {}curly braces is nested . We have deconstructed the hobbyattribute above , and then continue to deconstruct the nameattribute and assign the default value to it, and then we give it an alias variable code.

Attention should be paid to object deconstruction minefields

You need to pay attention when using multi-level nested destructuring. You may accidentally create an invalid expression, that is, destructuring empty curly braces. But this syntax is also legal, and it will do nothing and report an error. Let's take a look below.

let person = {
    name: "蛙人",
    age: 24,
    hobby: {
    	name: "写代码"
    }
}
let { hobby: {} } = person

In the above statement, you can see that there hobbyis a {}bracket on the right side of the deep deconstruction property , but no variable is declared. This statement is also reasonable and will not report an error. Official answer: This grammar may be discarded in the future, as long as we know not to write it like this.


Array destructuring

Array deconstruction syntax is similar to object deconstruction syntax, except that array deconstruction uses []literal syntax to deconstruct. See the following example.

let colors = ["red", "blue", "green"]
let [ red, blue ] = colors
console.log(red, blue) // red blue

The biggest difference between array deconstruction and object deconstruction, object deconstruction is disordered while array deconstruction is ordered , let's look at the following example.

let colors = ["red", "blue", "green"];
let [ blue ] = colors
console.log(blue) // red

let ObjColors = {
    
    
    red: "red",
    blue: "blue",
    green: "green"
}
let {
    
     blue } = objColors
console.log(blue) // blue

In the above example, we can see that the bluevariables of the array deconstruction are redvalues, so the array deconstruction is based on the position. A position corresponds to a value. We can't get the value in the object like the object literal. We don’t need to follow order. The array deconstruction is the order of deconstruction required.

If we only want to get the second value of the array, we can ignore the variable of the first value and just write a placeholder. Look at the following example

let colors = ["red", "blue", "green"]
let [ , blue ] = colors
console.log(blue) // blue

In the above example, only the second value is obtained, so the first value of the array is deconstructed and the variable is not declared, and then the bluevariable is written , so that only the second value can be obtained.

Array deconstruction is the same as object deconstruction. The array deconstruction declared by var, let, and const must be initialized, otherwise an error will be thrown. I have already said it when I deconstructed the opposite side above, remember.

Array destructuring default value

The default value of array deconstruction is the same as the default value of object deconstruction. As long as there is no such value in the array or the value is set, undefinedthe default value will take effect.

let person = ["蛙人", 24]
let [ name, age, sex = "male" ] = person
console.log(name, age, sex) // 蛙人 24 male

Array multi-level nesting deconstruction

Array multi-level nesting deconstruction is similar to object multi-level nesting deconstruction, that is, the syntax is different, and arrays []are deconstructed in order. Let's take a look at an example

let person = ["蛙人", 24, ["写代码", "撩妹", "羽毛球"]]
let [ name, age, [firstHobby] ] = person
console.log(name, age, firstHobby) // 蛙人 24 写代码

In the above example, you can see that when multi-layer deconstruction is used, []square brackets are used to go deeper and deeper, and extract the data we want layer by layer.

The syntax of array deconstruction and object deconstruction are almost similar, just pay attention to the use of array deconstruction [], object deconstruction use {}, and their minefields are also the same. If I use deconstruction, I must initialize the value on the right side, otherwise an error will be reported.

Mixed deconstruction

That's it. The above is all about single object deconstruction, so we can now do some mixed deconstruction, which requires both data deconstruction and object deconstruction. Look at the following example

let person = {
    
    
    name: "蛙人",
    age: 24,
    sex: "male",
    hobby: ["写代码", "撩妹", "羽毛球"]
}
let {
    
     name, sex, hobby: [, , lastHobby] } = person
console.log(name, sex, lastHobby) // 蛙人 male 羽毛球

In the above example, it personis an object with personal information defined. Then in the following deconstruction, object deconstruction and array deconstruction are used, and then we know that array deconstruction can only be deconstructed based on position, so we use array placeholders to get the value of the last array.

So where are so many grammars mentioned above? In what kind of scenarios should it be used? Let's take a look at these grammar application scenarios

Application scenarios

Object deconstruction

Usually in Es5, for example, if we want to have a personal information display function, we first write a function and then pass an object. In this function, we need to declare and assign a bunch of variables, and these values ​​are all from the object passed in. take. Look at the following example

function informationFn(data) {
    
    
    let name = data.name;
    let age = data.age;
    let sex = data.sex;
    let email = data.email;
    let phone = typeof data.phone != "undefined" ? data.phone : "暂无";
}
let person = {
    
    
    name: "蛙人",
    age: 24,
    sex: "男",
    email: "[email protected]",
    phone: undefined
}
informationFn(person)

In the above example, you can see that although there is no problem with the code, there is too much code in this way, resulting in code redundancy. Now we are using Es6 syntax to implement the above functions.

function informationFn({ name, age, sex, email, phone = "暂无" }) {
    console.log(name, age, sex, email, phone)
}
let person = {
    name: "蛙人",
    age: 24,
    sex: "男",
    email: "[email protected]",
    phone: undefined
}
informationFn(person)

In the above example, we used the Es6 syntax object deconstruction and deconstruction default value to achieve it again, you can see that the code is very concise.

Array destructuring and assignment

In Es5, we want to achieve a value exchange between two variables, we have to rely on the first variable to achieve.

let a = 1;
let b = 2;
let temp;
temp = a;
a = b;
b = temp;
console.log(a, b) // 2 1

However, in Es6, there is no need to do the array destructuring assignment. Let's see how to implement it.

let a = 1;
let b = 2;
[ a, b ] = [b, a]
console.log(a, b)

In the above example, the expression on the right side of the destructuring assignment is a temporary array. It will first calculate the right side array, and finally assign the right side array to the previous array variable.

thank

Thank you for opening this article during your busy schedule. I hope it will be helpful to you. If you have any questions, you are welcome to correct me.

If you think it's okay, just give it a thumbs-up for it. ??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

Are interested, you can also add my personal vx exchange contact me

Guess you like

Origin blog.csdn.net/weixin_44165167/article/details/114076269