search
HomeWeb Front-endJS TutorialTake you to understand JavaScript destructuring assignment

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]

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

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

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

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;
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

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
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

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]
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

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

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'
*/
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

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
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

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

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"

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

// x = undefined
// y = 'world'

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}

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'

Notes

Be careful when using declared variables for destructuring

Error demonstration:

let x;{x} = {x: 1};
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});
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]);
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];

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();

提取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]

使用上面的代码,我们就可以快速取出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!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment