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
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft