search
HomeWeb Front-endJS TutorialDetailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

This article brings you relevant knowledge about javascript, which mainly organizes issues related to destructuring and assigning objects and arrays, including array destructuring, object destructuring, function parameter parsing, etc. Let’s take a look at the content below. I hope it will be helpful to everyone.

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

[Related recommendations: javascript video tutorial, web front-end

Object (Object ) and array (Array) are the two most commonly used data structures in JavaScript. The common feature of both is that they can store a large amount of data.

The problem is that when we pass parameters and calculate them, we may only need part of the object and array, not the entire object/array.

At this time, you need to use Destructuring assignment to unpack the object/array and obtain part of its internal data. The following uses cases to introduce the application of destructuring assignment in programming.

Array destructuring

The so-called array destructuring is to obtain part of the data that is useful to us in the array. For example:

let arr = ['first','second']let [x, y] = arr //解构操作console.log(x,y)

The code execution result is as follows:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

The content of the code is very simple. It assigns the contents of the array to two variables and then outputs them.

Array destructuring can also be used in conjunction with the split function, which is elegant and high-end:

let [x, y] = 'hello world'.split(' ')console.log(x, y)

The code execution results are as follows:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

Destructuring does not change the original array

Destructuring can also be called "destructuring assignment". Its essence is to copy the elements of the array to variables, so the original array does not change in any way.

let [x, y] = arr //{1}let x = arr[0]   //{2}let y = arr[1]

{1} and {2} in the above code are completely equivalent, but the destructuring and assignment method is more concise.

Ignore array elements

If we use destructuring assignment, we hope to get the 1, 3th element of the array, but not the first 2 elements, what should we do?

For example:

let [x, ,z] = ['first','second','third']console.log(x,z)

The code execution result is as follows:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

In this way, commas are used to avoid the second element.

Iterable objects use destructuring

Destructuring assignment is not necessarily used on arrays, it can be used on any iterable object, for example:

let [x, y, z] = 'xyz'let [a, b, c] = new Set(['a','b','c'])console.log(x,y,z)console.log(a,b,c)

Code Execution result:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

#Destructuring assignment will iterate the value on the right and then assign the value to the variable on the left.

Assign a value to any variable

The right side of the = of the destructuring assignment can be any and iterated object, while the left side can be any variable that can be assigned a value, and Not limited to simple variables.

Give a chestnut:

let country = {};[country.name, country.desc] = 'China Beautiful'.split(' ')console.log(country.name,country.desc)

Code execution result:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

Note: The points in the first line of code The number must be added, otherwise you will encounter an error! For details, you can learn about "JavaScript Syntax Structure".

Combined with the .entries() method

Object.entries(obj) method will return the attribute list of the object obj, we can also Destructuring syntax is used here:

let country = {
    name:'China',
    desc:'a beautiful country'}for(let[k, v] of Object.entries(country)){
    console.log(k,v)}

Code execution result:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

Combined with Map

Due to the Map object It is iterable itself, so you can directly use the for...of syntax combined with the destructuring syntax:

let map = new Map()map.set('name','China')map.set('desc','Beautiful Country')for(let [k, v] of map){
    console.log(k,v)}

Code execution result:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

Variable exchange

There is a famous technique for destructuring assignment, exchanging the values ​​​​of two variables:

let a = 1;let b = 2;[a,b]=[b,a]console.log(`a=${a},b=${b}`)

Code execution result:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

Extra elements

During the process of performing destructuring assignment, there are two situations:

  1. There are more elements on the left than on the right, and the value on the left uses undefinedFill;
  2. The elements on the right are more than the elements on the left. Ignore the excess. You can also use ... to collect;

There are more elements on the left than on the right :

let [a,b,c] = 'ab'console.log(a,b,c)

Code execution result:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

可见最后一个变量c被赋值undefined

我们也可以为多余的左侧变量赋予默认值,举个例子:

let[a=0,b=0,c=0] = 'ab'console.log(c)

代码执行结果如下:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

右侧多于左侧:

let [a, b] = 'abcd'console.log(a,b)

代码执行结果如下:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

这里就没什么可解释的了。

但是,如果我们希望获得其他元素应该怎么做呢?

举例如下:

let [a, b, ...others] = 'abcdefg'console.log(others)

代码执行结果:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

这里的变量others就将所有剩余选项全部都收集了起来,others可以是任何合法的变量名,不局限于others本身。

对象解构

解构语法同样使用于对象,只不过语法上稍有不同:

let {var1, var2} = {...}

举个例子:

let country = {
    name:'China',
    desc:'Beautiful'};let {name,desc} = country;console.log(name,desc)

代码执行结果:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

**注意:**这里的变量顺序是没有影响的,我们也可以交换namedesc的位置,如:

let {desc,name}=country;

代码的执行结果并没有什么变化。

属性变量映射

当然我们也可以指定变量和属性的映射,例如:

let country = {
    name:'China',
    desc:'Beautiful'}//对应的规则:{对象属性:目标变量}let {name:desc,desc:name} = country;console.log(`name:${name},desc:${desc}`)

代码执行结果:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

这样我们就强行交换了变量和属性之间的映射方式,或许下面的例子更直观:

let obj = {
    x:'xiaoming',
    y:'18'}let {x:name,y:age}=obj;console.log(`name:${name},age:${age}`)

代码执行结果:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

默认值

和数组一样,我们也可以使用=为变量指定默认值。

举例如下:

let obj = {
    name:'xiaoming',
    age:18}let {name='xiaohong',age=19,height=180} = obj
console.log(height)

代码执行结果:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

这样,即使对象没有对应的属性,我们同样可以使用默认值代替。

我们还可以结合映射和默认值:

let obj = {
    x:'xiaoming',
    y:'18'}let {x:name='xxx',y:age=18,height:height=180}=obj;console.log(`name:${name},age:${age},height:${height}`)

代码执行结果:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

多余的属性

和数组一样,我们可以取对象的一部分属性:

let obj = {
    x:'x',
    y:'y',
    z:'z'}let {x:name}=obj
console.log(name)

我们还可以使用...将剩余的属性重新打包为一个新对象:

let obj = {
    x:'x',
    y:'y',
    z:'z'}let {x,...others}=obj
console.log(others)

代码执行结果:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

let陷阱

可能有写童鞋已经发现了,我们在使用解构操作时,总是把一个对象赋值给一个使用let新定义的变量,例如:let {...} = obj

如果我们使用已经存在的对象,会发生什么事呢?

let a,b,c;//定义三个变量{a,b,c} = {a:'a',b:'b',c:'c'}console.log(a,b,c)

代码执行结果如下:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

为什么会出现这种错误呢?

这是因为JavaScript会把主代码流中的{...}作为一个代码块,代码块是一个独立的代码空间,用于语句的分组。

案例如下:

{
    let a = 1;
    let b = 2;
    ...}

上例中的{a,b,c}就被错误的当成了这样的代码块,为了告诉引擎这不是一个代码块,我们可以这样:

let a,b,c;//定义三个变量({a,b,c} = {a:'a',b:'b',c:'c'})//加括号console.log(a,b,c)

代码执行结果如下:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

多层解析

如果对象出现了嵌套,相应的我们也可以使用对应的嵌套层次进行解析:

let People = {
    head:{
        leftEye:'le',
        rightEye:'re'
    },
    hands:['left-hand','right-hand'],
    others:'others'}let {
    head:{
        leftEye,
        rightEye    },
    hands:[left_hand,right_hand],
    others} = People;console.log(leftEye,right_hand)

代码执行结果:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

函数参数解析

有些情况下,一个函数需要非常多的参数,这不仅会让程序猿记忆困难,同时也会让代码变的冗长。

例如:

function createWin(title="Untitled",width=100,height=200,items=[]){
    ...}

这种情况下,调用函数会变的非常困难。更令人苦恼的是,通常这些参数只要保持默认就可以了,而我们还要费尽心机的重写它们。就像这样:

createWin(title="Untitled",width=100,height=200,items=['i','j','k'])

解构赋值可以帮助我们解决这些问题,我们可以把对象传递给函数,而函数会自动的把对象解析为参数:

let options = {
    title:'NewWin',
    width:200,
    height:100,
    items:['items1','items2']}//传入的对象会被解构成下面的参数样式//等价于{title="Untitled",width=100,height=200,items=[]} = optionsfunction createWin({title="Untitled",width=100,height=200,items=[]}){
   	  console.log(`title:${title},width:${width},height:${height},items:[${items}]`)}createWin(options)//只需要传递一个对象

【相关推荐:javascript视频教程web前端

The above is the detailed content of Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays. 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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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 Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft