This is the 19th day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021

Array.prototype.splice()/slice()/map()/reduce() etc. Learn a direct list of some of these amazing “bugs” here

In project development, the data at the back end of the request are mostly objects/arrays, and we often need to process this “large” data to get the data structure we want. In this article, we will learn a relatively advanced manipulation of ES6: deconstructing assignment.

ES6 – Deconstruct assignment

Concept:

The destruct assignment syntax is a Javascript expression. By deconstructing assignments, attributes/values can be taken from objects/arrays and assigned to other variables.

Destructuring Assignment is a compound declaration and assignment syntax that ES6 began to implement

Let’s start with a simple example:

let [a, b] = [10.20]

letrest ; [a, b, ...rest] = [10.20.30.40.50]
Copy the code

// let a = 10, b = 20 // rest is an array: [30, 40, 50]

explain

To understand this from the simple example above: In a deconstructed assignment, the value to the right of the equals sign (=) is an array or object (both of which are “structured values “), while the left hand side is one or more variables specified by emulating array or object literal syntax.

During deconstruction, data (one or more values) is extracted from the raw data on the right and corresponding values are assigned to the variables on the left;

Destruct assignment

  1. Destruct assignment is used in const/ let/ var declarations to initialize variables

    Example above

  2. It can also be used in regular assignment expressions.

  3. It is also useful in function parameter definition

  4. Handles arrays/objects returned by functions (usually data requested from the back end)

    It is quite common to return an array from a function: for example, when a function returns an array, it is convenient to use destruct assignment to evaluate

Parses an array returned from a function:


function returnArrayData(x, y) {
  return [x, y]
}
let [x, y] = returnArrayData(111.222)
// let [x, y] = [111, 222]
// this is equivalent to x = 111, y = 222
Copy the code

List of related reading articles

  • JavaScript Learning – Function remaining arguments
  • JS small problem learning – function optional argument
  • JS learning -for loop
  • JS imperfect can also run – auto add semicolon (;) The problem,
  • JS imperfect can also run – array object addition problem,
  • JS imperfect arrow function correlation (2),
  • JS is not perfect
  • JavaScript Higher-order functions (1)
  • Reduce for JavaScript higher-order functions
  • Array.prototype.flat()
  • Flexible manipulation of array data Slice ()
  • Insert data in the middle of array splice()

Reference documentation

  • MDN | ES6-Destructuring_assignment