Related recommendations: JavaScript learning tutorial
ES6 provides a more concise assignment mode to extract values from arrays and objects, which is called destructuring
Example:
[a, b] = [50, 100]; console.log(a); // expected output: 50 console.log(b); // expected output: 100 [a, b, ...rest] = [10, 20, 30, 40, 50]; console.log(rest); // expected output: [30, 40, 50]
Array destructuring is very simple and concise. Use an array literal on the left side of the assignment expression. Each variable name in the array literal maps to the same index of the destructured array.
What doesthe item
mean? Just like the example below, the items in the array on the left get the values of the corresponding indexes of the destructured array on the right
let [a, b, c] = [1, 2, 3]; // a = 1 // b = 2 // c = 3
You can deconstruct the assignments separately through variable declarations.
Example: declare variables, assign values separately
// Declare variables let a, b; // Then assign values [a, b] = [1, 2]; console.log(a); // 1 console.log(b); // 2
If the value taken out by destructuring is undefined
, you can set the default value:
let a, b; // Set default value [a = 5, b = 7] = [1]; console.log(a); // 1 console.log(b); // 7In
the above example, we set default values for both a and b. In this case, if the value of a or b is undefined
, it will assign the set default value to the corresponding Variables (5 is assigned to a, 7 is assigned to b)
In the past, when we exchanged two variables, we always used
//exchange abc = a;a = b;b = c;
or the XOR method
. However, in deconstruction In assignment, we can exchange the values of two variables in a destructuring expression
let a = 1; let b = 3;//Exchange the values of a and b [a, b] = [b, a]; console.log( a); // 3console.log(b); // 1
We can directly deconstruct a function that returns an array
function c() { return [10, 20];}let a, b;[a, b] = c();console.log(a); // 10console.log(b); // 20
In the above example, ** The return value [10, 20] of c()** can be used in a separate line of code
You can selectively skip some unwanted return values
function c () { return [1, 2, 3];}let [a, , b] = c();console.log(a); // 1console.log(b); // 3
when you When using array destructuring, you can assign all the remaining parts of the assigned array to a variable
let [a, ...b] = [1, 2, 3];console.log(a); // 1console.log(b ); // [2, 3]
In this case, b will also become an array, and the items in the array are all the remaining items.
Note:
Be careful here that you cannot write a comma at the end. If there is an extra comma, an error will be reported
let [a, ...b,] = [1, 2, 3];// SyntaxError: rest element may not have a trailing comma
Like objects, arrays can also be nested.
Example:
const color = ['#FF00FF', [255, 0, 255], 'rgb(255, 0, 255)']; // Use nested destructuring to assign red, green and blue // Use nested destructuring to assign red, green, blue const [hex, [red, green, blue]] = color; console.log(hex, red, green, blue); // #FF00FF 255 0 255
In array destructuring, if the target of destructuring is a traversable object, destructuring and assignment can be performed. The traversable object implements the Iterator interface Data
let [a, b, c, d, e] = 'hello';/* a = 'h' b = 'e' c = 'l' d = 'l' e = 'o' */
let x = { y: 22, z: true }; let { y, z } = x; // let {y:y,z:z} = abbreviation for x; console.log(y); // 22 console.log(z); // true
The name of the variable can be changed when using object destructuring
let o = { p: 22, q: true }; let { p: foo, q: bar } = o; console.log(foo); // 22 console.log(bar); // true
code as above var {p: foo} = o
gets the property name p of object o, and then assigns it to a variable named foo.
. If the object value taken out by destructuring is undefined
, we You can set the default value
let { a = 10, b = 5 } = { a: 3 }; console.log(a); // 3 console.log(b); // 5
As mentioned earlier, we assign a value to the new object name. Here we can provide a default value for the new object name, if it is not deconstructed. , the default value will be automatically used
let { a: aa = 10, b: bb = 5 } = { a: 3 }; console.log(aa); // 3 console.log(bb); // 5
Arrays and objects can be used together in structures
const props = [ { id: 1, name: 'Fizz' }, { id: 2, name: 'Buzz' }, { id: 3, name: 'FizzBuzz' }, ]; const [, , { name }] = props; console.log(name); // "FizzBuzz"
let obj = {p: [{y: 'world'}] }; let {p: [{ y }, x ] } = obj;//Do not deconstruct x // x = undefined // y = 'world'
let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}; // a = 10 // b = 20 // rest = {c: 30, d: 40}
let obj = {p: ['hello', {y: 'world'}] }; let {p: [x, { y }] } = obj; // x = 'hello' // y = 'world' let obj = {p: ['hello', {y: 'world'}] }; let {p: [x, { }] } = obj;//ignore y // x = 'hello'
error demonstration:
let x;{x} = {x: 1};
The JavaScript engine will understand {x}
as a code block, resulting in a syntax error, We want to avoid writing the curly braces at the beginning of the line to prevent JavaScript from interpreting them as a code block
of
writing
:
let
function add([x, y]) { return x + y;}add([1, 2]);
In the above code, the parameter of function add is an array on the surface, but when passing the parameter, the array parameter is deconstructed into variables x and y. For the function Internally, it is the same as directly passing in x and y.
The use of destructuring isuse of destructuring assignment. There are many ways
let x = 1; let y = 2; [x, y] = [y, x];
The above code exchanges the values of x and y. This writing method is not only concise but also easy to read, and the semantics are clear.
can only return one value. If you want to return multiple values values, we can only put these values in an array or object and return them. When we have destructuring assignment, taking these values from the object or array is like searching for something
// Return an array function example() { return [1, 2, 3];}let [a, b, c] = example(); // Return an object function example() { return { foo: 1, bar: 2 }; }let { foo, bar } = example();
destructuring assignment is particularly useful for extracting data in JSON objects.
Example:
let jsonData = { id: 42, status: "OK", data: [867, 5309] }; let { id, status, data: number } = jsonData; console.log(id, status, number); // 42, "OK", [867, 5309]
Using the above code, we can quickly retrieve the value in the JSON data.
Related recommendations: JavaScript tutorial
The above is to take you to understand the details of JavaScript destructuring assignment. For more information, please pay attention to php Other related articles on the Chinese website!