JavaScript column introduces how to use object deconstruction
Object destructuring is a useful JavaScript feature that can extract properties from an object and bind them to variables. Even better, object destructuring can extract multiple properties in a single statement, properties can be accessed from nested objects, and a default value can be set if the property does not exist. In this article, I will explain how to use object decomposition in JavaScript. Directory1.Require object decomposition##Related free learning recommendations: javascript (Video)
2.Extract attributes
3.Extract multiple attributes
4.Default value
5.Alias
6. Extract attributes from nested objects
7. Extract dynamic name attributes
8. Destroyed objects
9. Common use cases
10. Summary
var hero = { name: 'Batman', realName: 'Bruce Wayne' }; var name = hero.name;var realName = hero.realName; name; // => 'Batman', realName; // => 'Bruce Wayne'Property
hero.nameThe value is assigned to the variable
name. Assign the same
hero.realName value to
realName.
var name = hero.name, you have to mention
name twice in the binding, for the same
realName.
name and
realName:
const hero = { name: 'Batman', realName: 'Bruce Wayne' }; const { name, realName } = hero; name; // => 'Batman', realName; // => 'Bruce Wayne'
const { name , realName } = hero is the object destruction and allocation. This statement defines the variables
name and
realName, and then assigns to their attribute values
hero.name and
hero.realNamecorrespondigly.
const name = hero.name; const realName = hero.realName; // is equivalent to: const { name, realName } = hero;It can be seen that since the property names and object variables are not repeated, the decomposition of the object is more convenient. 2. Extract attributes The basic syntax for object destructuring is very simple:
const { identifier } = expression;where
identifier is the name of the property to be accessed,
expression Should evaluate to an object. After destruction, the variable
identifier contains the attribute value.
const identifier = expression.identifier;Let's try object decomposition in practice:
const hero = { name: 'Batman', realName: 'Bruce Wayne' }; const { name } = hero; name; // => 'Batman'The statement
const { name } = herodefines the variable
name and initializes it with the value of
hero.nameproperty.
,add commas in between:
const { identifier1, identifier2, ..., identifierN } = expression;where
identifier1,...
identifierN are the names of the properties to be accessed and the
expression should evaluate to objects. After destruction, the variables
identifier1…
identifierN contain the corresponding attribute values.
const identifier1 = expression.identifier1; const identifier2 = expression.identifier2; // ... const identifierN = expression.identifierN;Let’s look at the example from the first part again, where 2 properties are extracted:
const hero = { name: 'Batman', realName: 'Bruce Wayne' }; const { name, realName } = hero; name; // => 'Batman', realName; // => 'Bruce Wayne'
const { name, realName } = hero Create 2 variables
name and
realName assign the corresponding attributes
hero.name and the value of
hero.realName.
undefined. Let's see how it happens:
const hero = { name: 'Batman', realName: 'Bruce Wayne' }; const { enemies } = hero; enemies; // => undefinedThe destructured variable
enemies is
undefined because the property
enemies is not in the object
hero exists.
const { identifier = defaultValue } = expression;where
identifier is the name of the property to be accessed and
expression should evaluate to an object. After destruction, the variable
identifier contains the attribute value, or
defaultValue is assigned to the variable if the
identifier attribute does not exist.
const identifier = expression.identifier === undefined ? defaultValue : expression.identifier;Let’s change the previous code example and use the default value function:
const hero = { name: 'Batman', realName: 'Bruce Wayne' }; const { enemies = ['Joker'] } = hero; enemies; // => ['Joker']Now,
undefined The variable
enemies defaults to
['Joker'].
const { identifier: aliasIdentifier } = expression;
identifier is the name of the property to be accessed,
aliasIdentifier is the name of the variable, and
expression should evaluate to an object. After destruction, the variable
aliasIdentifier contains the attribute value.
const aliasIdentifier = expression.identifier;This is an example of object decomposition alias functionality:
const hero = { name: 'Batman', realName: 'Bruce Wayne' }; const { realName: secretName } = hero; secretName; // => 'Bruce Wayne'
看一下const { realName: secretName } = hero
,解构定义了一个新变量secretName
(别名变量),并为其分配了值hero.realName
。
6.从嵌套对象中提取属性
在前面的示例中,对象很简单:属性具有原始数据类型(例如字符串)。
通常,对象可以嵌套在其他对象中。换句话说,某些属性可以包含对象。
在这种情况下,您仍然可以从深处使用对象分解和访问属性。基本语法如下:
const { nestedObjectProp: { identifier } } = expression;
nestedObjectProp
是保存嵌套对象的属性的名称。identifier
是要从嵌套对象访问的属性名称。expression
应该评估变形后的对象。
销毁后,变量identifier
包含嵌套对象的属性值。
上面的语法等效于:
const identifier = expression.nestedObjectProp.identifier;
您可以从中提取属性的嵌套级别不受限制。如果要从深处提取属性,只需添加更多嵌套的花括号:
const { propA: { propB: { propC: { .... } } } } = object;
例如,对象hero
包含一个嵌套对象{ city: 'Gotham'}
。
const hero = { name: 'Batman', realName: 'Bruce Wayne', address: { city: 'Gotham' } }; // Object destructuring: const { address: { city } } = hero; city; // => 'Gotham'
通过对象解构,const { address: { city } } = hero
您可以city
从嵌套对象访问属性。
7.提取动态名称属性
您可以将具有动态名称的属性提取到变量中(属性名称在运行时是已知的):
const { [propName]: identifier } = expression;
propName
expression应该计算为属性名称(通常是字符串),并且identifier
应该指示在解构之后创建的变量名称。第二个expression
应该评估要分解的对象。
没有对象分解的等效代码:
const identifier = expression[propName];
让我们看一个prop
包含属性名称的示例:
const hero = { name: 'Batman', realName: 'Bruce Wayne' }; const prop = 'name'; const { [prop]: name } = hero; name; // => 'Batman'
const { [prop]: name } = hero
是一个对象分解,将变量赋给name
value hero[prop]
,其中prop
是一个保存属性名称的变量。
8.销毁后的物体
rest语法对于在解构之后收集其余属性很有用:
const { identifier, ...rest } = expression;
哪里identifier
是要访问的属性名称,expression
应评估为一个对象。
销毁后,变量identifier
包含属性值。rest
变量是具有其余属性的普通对象。
例如,让我们提取属性name
,但保留其余属性:
const hero = { name: 'Batman', realName: 'Bruce Wayne' }; const { name, ...realHero } = hero; realHero; // => { realName: 'Bruce Wayne' }
破坏const { name, ...realHero } = hero
提取财产name
。
同时,剩余的属性(realName
在这种情况下)被收集到变量realHero
:中{ realName: 'Bruce Wayne' }
。
9.常见用例
9.1将属性绑定到变量
如之前的许多示例所示,对象解构将属性值绑定到变量。
对象解构可以给变量赋值使用声明const
,let
和var
。甚至分配给一个已经存在的变量。
例如,以下是使用let
语句解构的方法:
// let const hero = { name: 'Batman', }; let { name } = hero; name; // => 'Batman'
如何使用var
语句来破坏结构:
// var const hero = { name: 'Batman', }; var { name } = hero; name; // => 'Batman'
以及如何解构为已声明的变量:
// existing variable let name; const hero = { name: 'Batman', }; ({ name } = hero); name; // => 'Batman'
我发现将for..of
循环与对象解构相结合以立即提取属性是令人满意的:
const heroes = [ { name: 'Batman' }, { name: 'Joker' } ]; for (const { name } of heroes) { console.log(name); // logs 'Batman', 'Joker' }
9.2功能参数解构
通常,对象分解可以放置在发生分配的任何位置。
例如,您可以在函数的参数列表内破坏对象:
const heroes = [ { name: 'Batman' }, { name: 'Joker' } ]; const names = heroes.map( function({ name }) { return name; } ); names; // => ['Batman', 'Joker']
function({ name })
解构函数参数,创建一个name
保存name
属性值的变量。
10.总结
对象解构是一项强大的功能,可让您从对象中提取属性并将这些值绑定到变量。
我特别喜欢对象分解的简洁语法和在一条语句中提取多个变量的能力。
希望我的帖子对您了解对象分解的有用!
The above is the detailed content of Master summarizes how to use object destructuring in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

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

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

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.