If the profile

Since I just started to write an article last week, I set a flag here. I insist to write at least one article on ES grammar every week to improve my foundation. The last article was about the new declaration method in ES6, link: juejin.cn/post/699405… , this time about deconstructing assignment in ES6. If there is wrong or inaccurate place, welcome everyone to put forward 😄, I also actively modify. Below begins the body:

The body of the

A new method of variable assignment has been added in ES6: destruct assignment. Allows you to extract values from arrays and objects and assign values to variables in a pattern. The code is as follows:

Let arr = [1,2,3] let a = arr[0] let b = arr[1] let c = arr[2]Copy the code

In the above code, declare an array arr, and assign values from the array to a, B, and C, as in ES6

Let [a, b, c] = [1, 2, 3]Copy the code

TIP deconstructs the assignment mainly in the assignment, the assigned element is to be copied and assigned to the variable, the assigned element itself is not changed.

Object and Array are most commonly used in destructuring assignments. Let’s take a look at how destructuring assignments work for both.

Array destruct assignment

  • The assignment element can be any traversable object

    The assigned element is not just an array; it can be any traversable object
    Let (a, b, c) = 'ABC' in the console, log (a, b, c) / / 'a' 'b' 'c' let [x, y, z] = new Set ([1, 2, 3]) console. The log (a, b, c) / / 1 2 3Copy the code
  • The variable on the left

    The assigned variable can also be a property of an object, not just a variable.
    Let user = {} [user.firstName, user.secondName, user.thirdName] = ' '.split(' ') console.log(user.firstName, user.secondName, user.thirdName) User.secondname, user.thirdName) // console.log(user) // {firstName: "", secondName:" ", thirdName: ""}Copy the code
  • The loop body

    The use of deconstructed assignments in the body of a loop can be used with entries.
    Let user = {name:' liu neng ', } for(let [key,value] of object.entries (user)){console.log(' ${key}:${value} ')}Copy the code
  • You can skip the assignment element

    If you want to assign to a variable by ignoring an element of the array, use a comma.
    let [name,,age] = ['xs','boy',18,'guitar']
    console.log(age) // 18
    Copy the code
  • Rest parameters

    let [name,age,...rest] = ['xs',18,'boy','guitar']
    console.log(name) // 'xs'
    console.log(age) // 18
    console.log(rest) //['boy','guitar']
    console.log(rest[0]) // 'boy'
    console.log(rest[1]) // 'guitar'
    console.log(rest.length) // 2
    Copy the code

    Note that we can use rest to accept the rest of the assignment array, but make sure that the rest argument is placed in the last position of the assigned variable.

  • The default value

    If the contents of the array are less than the number of variables, no error is reported. Variables that are not allocated to the contents are undefined.
    let [name ,age] = []
    console.log(name) // undefined
    console.log(age) // undefined
    
    let [a, b, c] = [1, 2]
    console.log(a, b, c)// 1  2  undefind
    Copy the code

    You can also give variables default values to prevent undefined:

    let [name = 'xs', age = 18] = ['Kobe Bryant']
    console.log(name) // 'Kobe Bryant'
    console.log(age) // 18
    Copy the code

When you do an assignment, it takes the assigned value, if you don’t do an assignment, it takes the default value, and if it doesn’t, it defaults to undefind. So we can prove that the array assignment is based on the index value of the array subscript

The following example verifies that an array assignment is lazy

function foo () {
  console.log(123)
}

let [a = foo()] = [1]
Copy the code

In the above code, the console will not print 123 printed in foo if the array assigned to the right has element 1 in it, and will print 123 printed in foo if the array assigned to the right is an empty array []. Therefore, you can verify that an array assignment is lazy.

Object destruct assignment

  • Basic usage Destruct assignment can be applied to objects as well as arrays. The basic syntax is as follows:

    Let {var1, var2} = {var1:… , var2… }

    We declare an Object and want to separate its properties without assigning them to the specified variable by calling the properties. To do this, declare a template equivalent to the Object structure on the left side of the assignment, and then specify the value of the desired attribute as the new variable.

    let obj = {
      name: 'xs',
      age: 18,
      like: 'music'
    }
    let { name, age, like } = obj
    console.log(name) // 'xs'
    console.log(age) // 18
    console.log(like) // 'music'
    Copy the code

    TIP During the assignment of this structure, the “template” structure on the left should be the same as the Object structure on the right, but the order of attributes need not be the same.

    The left side of the assignment is an object shorthand, like this:

    let {name: name, age: age, like: like} = obj
    Copy the code

    If you don’t want to write it this way or want to use another variable name, you can customize it as follows:

    let {name: uname, age: uage, like} = obj
    Copy the code
  • You can also specify a default value during assignment, as follows:

    let obj = {
      name: 'xs',
    }
    let {name,age = 18,like='music'} = obj
    console.log(name) // 'xs'
    console.log(age) // 18
    console.log(like) // 'music'
    Copy the code
  • Rest operators Are used if you only need the specified attributes and the rest can be temporarily stored in a variable

    let obj = { name: 'xs', age: 18, like: 'music' } let { name, ... rest} = obj console.log(name) // 'xs' console.log(rest) // {age: 18,like: 'music'}Copy the code
  • Nested Objects If an Array or Object is complex and has nested arrays or objects, it is fine as long as the structure of the assignment is the same as that of the element assigned to the right.

    let obj = {
      userName: 'xs',
      age: 18,
      like: {
        type:'sports',
        likeName:'basketball'
      },
      music:['Light music','rock music'],
    }
    let {
      userName,
      age,
      like: {
        type,
        likeName
      },
      music:[type1,type2],
      sex='male'
    } = obj
    console.log(type) // 'sports'
    console.log(likeName) // 'basketball'
    console.log(type1) // 'Light music'
    console.log(type2) // 'rock music'
    console.log(sex) // 'male'
    Copy the code

String destruct assignment

The deconstruction assignment of strings can be understood as the deconstruction assignment of arrays

let str = 'string'
for (let i = 0; i < str.length; i++) {
  console.log(str[i])
}
Copy the code

Equivalent to the following code:

let [a, b, c, d, e, f] = 'string'
console.log(a, b, c, d, e, f)
Copy the code

Function destruct assignment

  • The function takes a destruct assignment to the array
    function foo ([a, b, c]) {
      console.log(a, b, c) // 1  2  3
    }
    let arr = [1, 2, 3]
    foo(arr)
    Copy the code
  • Function arguments are assigned to the deconstruction of the object
    function foo ({ name, age , sex='male'}) {
      console.log(name, age) // 'xs'  18
    }
    let obj = {
      name: 'xs',
      age: 18
    }
    foo(obj)
    Copy the code

    In the code abovesexAttribute is an attribute that can be transmitted or not. If the value is not transmitted, the default value is'male'If a value is passed, the passed value is taken.

  • Destruct assignment of the return value of a function
    function foo ([a, b, c]) {
      let obj = {
        name: 'xs',
        age: 18,
        school:'xxx'
      }
      return obj
    }
    let {name,age,school} = foo()
    console.log(name,age,school) // 'xs' 18 'xxx'
    Copy the code

Deconstructed assignment of JSON data

The deconstruction assignment of JSON data can be understood in terms of the deconstruction assignment of objects

let json = '{"a":"hello","b":"world"}'
let { a, b } = JSON.parse(json)
console.log(a, b) // 'hello' 'world'
Copy the code