Home > Web Front-end > JS Tutorial > body text

Take you to understand JavaScript destructuring assignment

WBOY
Release: 2022-03-17 17:36:30
forward
2374 people have browsed it

This article brings you relevant knowledge about javascript, which mainly introduces related issues about destructuring assignment, including array destructuring, object structure and the use of destructuring, etc. I hope it will be helpful to you. Everyone is helpful.

Take you to understand JavaScript destructuring assignment

Related recommendations: javascript learning tutorial

Concept

ES6 provides a more concise assignment mode, starting from Extracting values ​​from arrays and objects 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]
Copy after login

Array destructuring

Array destructuring is very simple and concise. An array literal is used on the left side of the assignment expression. Each variable name in the array literal is mapped to the same index item of the destructured array.

What does this mean? Just like the example below, in the array on the left The items have respectively obtained the value of the corresponding index of the destructured array on the right

let [a, b, c] = [1, 2, 3];
// a = 1
// b = 2
// c = 3
Copy after login

Declaration of separate assignment

You can destructure and assign values ​​separately through variable declaration

Example : Declare variables and assign values ​​respectively

// 声明变量
let a, b;
// 然后分别赋值
[a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2
Copy after login

Destructuring default value

If the value taken out by destructuring is undefined, you can set the default value:

let a, b;
// 设置默认值
[a = 5, b = 7] = [1];
console.log(a); // 1
console.log(b); // 7
Copy after login

In 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 set the default value Assign to the corresponding variables (5 is assigned to a, 7 is assigned to b)

Exchange variable values

In the past, we used ## to exchange two variables. #

//交换abc = a;a = b;b = c;
Copy after login
or

XORmethod

However, in destructuring assignment, we can exchange two variable values ​​​​in a destructuring expression

let a = 1;let b = 3;//交换a和b的值[a, b] = [b, a];console.log(a); // 3console.log(b); // 1
Copy after login

Destructuring the array returned by the function

We can directly deconstruct a function whose return value is an array

function c() {
  return [10, 20];}let a, b;[a, b] = c();console.log(a); // 10console.log(b); // 20
Copy after login
In the above example, the return value of **c()**[ 10, 20] You can use destructuring in a separate line of code

Ignore the return value (or skip an item)

You can selectively skip Pass some unwanted return values

function c() {
  return [1, 2, 3];}let [a, , b] = c();console.log(a); // 1console.log(b); // 3
Copy after login

Assign the remaining value of the assignment array to a variable

When you use array destructuring, you can assign all the remaining parts of the assignment array Give a variable

let [a, ...b] = [1, 2, 3];console.log(a); // 1console.log(b); // [2, 3]
Copy after login
In this way, b will also become an array, and the items in the array are all the remaining items

Note: Be careful here 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
Copy after login

Nested array destructuring

Like objects, arrays can also be nested deconstructed

Example:

const color = ['#FF00FF', [255, 0, 255], 'rgb(255, 0, 255)'];
// Use nested destructuring to assign red, green and blue
// 使用嵌套解构赋值 red, green, blue
const [hex, [red, green, blue]] = color;
console.log(hex, red, green, blue); // #FF00FF 255 0 255
Copy after login

String destructuring

In array destructuring, if the target of destructuring is a traversable object, All can be deconstructed and assigned, and the object can be traversed, that is, the data that implements the Iterator interface

let [a, b, c, d, e] = 'hello';/*
a = 'h'
b = 'e'
c = 'l'
d = 'l'
e = 'o'
*/
Copy after login

Object destructuring

Basic object destructuring
let x = { y: 22, z: true };
let { y, z } = x; // let {y:y,z:z} = x;的简写

console.log(y); // 22
console.log(z); // true
Copy after login

Assignment Give the new variable name

You can change the name of the variable when using object destructuring

let o = { p: 22, q: true };
let { p: foo, q: bar } = o;

console.log(foo); // 22
console.log(bar); // true
Copy after login

The above code

var {p: foo} = o Get the object o The property name p is then assigned to a variable named foo

Destructuring default value

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
Copy after login

Assign the value to the new object name and provide the default value

As mentioned earlier, we assign the value to the new object name. Here we can give this The new object name provides a default value. If it is not destructured, the default value will be automatically used.

let { a: aa = 10, b: bb = 5 } = { a: 3 };

console.log(aa); // 3
console.log(bb); // 5
Copy after login

Use both array and object destructuring

In the structure, the array and Objects can be used together

const props = [
  { id: 1, name: 'Fizz' },
  { id: 2, name: 'Buzz' },
  { id: 3, name: 'FizzBuzz' },
];

const [, , { name }] = props;
console.log(name); // "FizzBuzz"
Copy after login

Incomplete destructuring
let obj = {p: [{y: 'world'}] };
let {p: [{ y }, x ] } = obj;//不解构x

// x = undefined
// y = 'world'
Copy after login

Assign the remaining value to an object

let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40};
// a = 10
// b = 20
// rest = {c: 30, d: 40}
Copy after login

Nested object destructuring (can be ignored Destructuring)
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;//忽略y
// x = 'hello'
Copy after login

Notes

Be careful when using declared variables for destructuring

Error demonstration:

let x;{x} = {x: 1};
Copy after login

The JavaScript engine will understand

{x} as a code block, resulting in a syntax error. We must avoid writing curly brackets at the beginning of the line to prevent JavaScript from interpreting it as a code block
Correct way of writing:

let x;({x} = {x: 1});
Copy after login

The correct way of writing is to put the entire destructuring assignment statement in a parentheses, and you can correctly execute the destructuring assignment of function parameters

The parameters of the function can also use destructuring assignment

function add([x, y]) {
	return x + y;}add([1, 2]);
Copy after login

In the above code, the parameter of the function add is an array on the surface, but when passing the parameter, the array parameter is destructured For the variables x and y, for the inside of the function, it is the same as directly passing in x and y

Uses of destructuring

There are many ways to use destructuring assignment

Exchange the value of the variable
let x = 1;
let y = 2;
[x, y] = [y, x];
Copy after login

The above code exchanges the values ​​of x and y. This writing method is not only concise but also easy to read and has clear semantics

Return from the function Multiple values

The function can only return one value. If we want to return multiple values, we can only return these values ​​​​in an array or object. When we have destructuring assignment, we can return it from the object or object. Retrieving these values ​​from the array is like picking something out of a bag

// 返回一个数组function example() {
  return [1, 2, 3];}let [a, b, c] = example();
  // 返回一个对象
  function example() {
  return {
    foo: 1,
    bar: 2
  };
  }let { foo, bar } = example();
Copy after login

提取JSON数据

解构赋值对于提取JSON对象中的数据,尤其有用

示例:

let jsonData = {
  id: 42,
  status: "OK",
  data: [867, 5309]
};

let { id, status, data: number } = jsonData;

console.log(id, status, number);
// 42, "OK", [867, 5309]
Copy after login

使用上面的代码,我们就可以快速取出JSON数据中的值

相关推荐:javascript教程

The above is the detailed content of Take you to understand JavaScript destructuring assignment. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!