Take 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.
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;
XORmethod
However, in destructuring assignment, we can exchange two variable values in a destructuring expressionlet 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 arrayfunction c() { return [10, 20];}let a, b;[a, b] = c();console.log(a); // 10console.log(b); // 20
Ignore the return value (or skip an item)
You can selectively skip Pass some unwanted return valuesfunction 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 variablelet [a, ...b] = [1, 2, 3];console.log(a); // 1console.log(b); // [2, 3]
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 deconstructedExample:
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 interfacelet [a, b, c, d, e] = 'hello';/* a = 'h' b = 'e' c = 'l' d = 'l' e = 'o' */
Basic object destructuringlet 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
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 destructuringlet o = { p: 22, q: true }; let { p: foo, q: bar } = o; console.log(foo); // 22 console.log(bar); // true
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 isundefined, 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 togetherconst props = [ { id: 1, name: 'Fizz' }, { id: 2, name: 'Buzz' }, { id: 3, name: 'FizzBuzz' }, ]; const [, , { name }] = props; console.log(name); // "FizzBuzz"
Incomplete destructuringlet obj = {p: [{y: 'world'}] };
let {p: [{ y }, x ] } = obj;//不解构x
// x = undefined
// y = 'world'
Copy after login
Assign the remaining value to an objectlet obj = {p: [{y: 'world'}] }; let {p: [{ y }, x ] } = obj;//不解构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}
Copy after login
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'
Copy after login
Noteslet 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'
Be careful when using declared variables for destructuring
Error demonstration:
let x;{x} = {x: 1};
{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 parameters of the function can also use destructuring assignment
function add([x, y]) { return x + y;}add([1, 2]);
Exchange the value of the variablelet 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 semanticslet x = 1; let y = 2; [x, y] = [y, x];
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
