Master summarizes how to use object destructuring in JavaScript
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'
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;
const { identifier } = expression;
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;
const hero = { name: 'Batman', realName: 'Bruce Wayne' }; const { name } = hero; name; // => 'Batman'
const { name } = herodefines the variable
name and initializes it with the value of
hero.nameproperty.
,add commas in between:
const { identifier1, identifier2, ..., identifierN } = expression;
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;
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; // => undefined
enemies is
undefined because the property
enemies is not in the object
hero exists.
const { identifier = defaultValue } = expression;
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;
const hero = { name: 'Batman', realName: 'Bruce Wayne' }; const { enemies = ['Joker'] } = hero; enemies; // => ['Joker']
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;
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!

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

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

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

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
