In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
The main content of this article is to explain "what is the JavaScript optional chain". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what the JavaScript optional chain is.
1. Due to the dynamic nature of JavaScript, an object can have a very different object nesting structure.
In general, you can deal with such objects in the following situations:
Get remote JSON data
Use configuration object
Have optional attribute
Although this gives objects the flexibility to support different data, it adds complexity when accessing the properties of such objects.
BigObject can have different property sets at run time:
/ / One version of bigObject const bigObject = {/ /... Prop1: {/ /... Prop2: {/ /... Value: 'Some value'}}; / / Other version of bigObject const bigObject = {/ /... Prop1: {/ / Nothing here}}
So you have to manually check whether the property exists:
/ / Later if (bigObject & & bigObject.prop1! = null & & bigObject.prop1.prop2! = null) {let result = bigObject.prop1.prop2.value;}
It's best not to write like this, because it contains too much boilerplate code.
Let's take a look at how the optional chain solves this problem, thereby reducing the template conditions.
two。 Easy in-depth access to properties
Let's design an object to save movie information. This object contains title required attributes, as well as optional director and actor.
The movieSmall object contains only title, while movieFull contains the complete set of properties:
Const movieSmall = {title: 'Heat'}; const movieFull = {title:' Blade Runner', director: {name: 'Ridley Scott'}, actors: [{name:' Harrison Ford'}, {name: 'Rutger Hauer'}]}
Let's write a function to get the name of the director. Note that the director property may be lost:
Function getDirector (movie) {if (movie.director! = null) {return movie.director.name;}} getDirector (movieSmall); / / = > undefined getDirector (movieFull); / / > 'Ridley Scott'
The if (movie.director) {...} condition is used to verify that the director attribute is defined. Without this precaution, JavaScript raises the error TypeError: Cannot read property 'name' of undefined when visiting the director of the movieSmall object.
This is the correct place to use the optional chain feature and remove the movie.director presence verification. The new version of getDirector () looks much shorter:
Function getDirector (movie) {return movie.director?.name;} getDirector (movieSmall); / / = > undefined getDirector (movieFull); / / = > 'Ridley Scott'
In the movie.director?.name expression, you can find the optional chain operator.
For movieSmall, missing attribute director. Results the calculated result of movie.director?.name was undefined. The optional chain operator prevents the TypeError: Cannot read property 'name' of undefined error from being raised.
On the contrary, the property director of movieFull is available. Movie.director?.name is evaluated as' Ridley Scott' by default.
In short, the code snippet:
Let name = movie.director?.name
Equivalent to:
Let name; if (movie.director! = null) {name = movie.director.name;}
?. The getDirector () function is simplified by reducing two lines of code. That's why I like optional chains.
2.1 Array items
The optional chain can do a lot more. You are free to use multiple optional chain operators in the same expression. You can even use it to securely access array items!
The next task is to write a function that returns the name of the main character in the movie.
Inside the movie object, the actor array can be empty or even missing, so you have to add other conditions:
Function getLeadingActor (movie) {if (movie.actors & & movie.actors.length > 0) {return movie.actors [0] .name;}} getLeadingActor (movieSmall); / / = > undefined getLeadingActor (movieFull); / / = > 'Harrison Ford'
If you need if (movie.actors & & movies.actors.length > 0) {...}, you must make sure that movie contains the actors attribute and that there is at least one actor in that attribute.
With optional chains, this task is easy to solve:
Function getLeadingActor (movie) {return movie.actors?. [0]? .name;} getLeadingActor (movieSmall); / / = > undefined getLeadingActor (movieFull); / / = > 'Harrison Ford'
Actors?. Make sure that the actors property exists. [0]?. Make sure that the first participant exists in the list. This is such a good thing!
3. Default is Nullish merge
A new proposal called the nullish merge operator deals with undefined or null, which is set to a specific value by default.
If variable is undefined or null, the expression variable? The result of defaultValue is defaultValue. Otherwise, the expression evaluates to the variable value.
Const noValue = undefined; const value = 'Hello'; noValue? 'Nothing'; / / = >' Nothing' value? 'Nothing'; / / = > 'Hello'
When the chain is evaluated as undefined, the Nullish merge can improve the optional chain by setting the default value to zero.
For example, let's change the getLeading () function to return "Unknown actor" when there are no actors in the movie object:
Function getLeadingActor (movie) {return movie.actors?. [0]? .name? 'Unknown actor';} getLeadingActor (movieSmall); / / = >' Unknown actor' getLeadingActor (movieFull); / / = > 'Harrison Ford'4. Three forms of optional chain
You can use the optional chain in the following three forms.
The first form of object.property is used to access static properties:
Const object = null; object?.property; / / = > undefined
The second form, object?. [expression], is used to access dynamic properties or array items:
Const object = null; const name = 'property'; object?. [name]; / / = > undefinedconst array = null; array?. [0]; / / = > undefined
Finally, the third form, object?. ([arg1, [arg2,...]]) Execute an object method:
Const object = null; object?.method ('Some value'); / / = > undefined
If desired, you can combine these forms to create a long optional chain:
Const value = object.maybeUndefinedProp?.maybeNull (). [propName]; 5. Short circuit: stop at null/undefined
The interesting thing about the optional chain operator is that once a null value is encountered on its left leftHandSide?.rightHandSide, it stops evaluating the right accessor. This is called a short circuit.
Look at an example:
Const nothing = null; let index = 0; nothing?. [index++]; / / = > undefined index; / / = > 0
Nothing leaves a null value, so the optional chain immediately evaluates to undefined and skips the evaluation of the right accessor. Because the value of index has not increased.
6. When to use optional chains
Resist the urge to use optional chain operators to access properties of any type: this can lead to incorrect usage. The next section explains when to use it correctly.
6.1 access attributes that may not be valid
?.: maybeNullish?.prop must be used only near attributes that may be empty. In other cases, use the old property accessor: .property or [propExpression].
Call the movie object. Looking at the expression movie.director?.name, because director can be undefined, it is correct to use the optional chain operator near the director attribute.
Instead, use?. There is no point in visiting the movie title movie?.title. The object of the movie will not be empty.
/ / Good function logMovie (movie) {console.log (movie.director?.name); console.log (movie.title);} / / Bad function logMovie (movie) {/ / director needs optional chaining console.log (movie.director.name); / / movie doesn't need optional chaining console.log (movie?.title);}
6.2 there is usually a better choice
The following function hasPadding () accepts a style object with an optional padding attribute. Padding has an optional property left,top,right,bottom.
Try using the optional chain operator:
Function hasPadding ({padding}) {const top = padding?.top? 0; const right = padding?.right? 0; const bottom = padding?.bottom? 0; const left = padding?.left? 0; return left + top + right + bottom! = = 0;} hasPadding ({color: 'black'}); / / > false hasPadding ({padding: {left: 0}}); / = > false hasPadding ({padding: {right: 10}}) / / = > true
Although the function can correctly determine whether the element has a fill, it is unnecessary to use an optional chain for each attribute.
A better approach is to use the object scatter operator to set the filled object to zero by default:
Function hasPadding ({padding}) {const p = {top: 0, right: 0, bottom: 0, left: 0,... padding}; return p.top + p.left + p.right + p.bottom! = = 0;} hasPadding ({color: 'black'}); / / > false hasPadding ({padding: {left: 0}}); / / = > false hasPadding ({padding: {right: 10}}); / / = > true
I think this version of hasPadding () is more readable.
7. Why do I like it?
I like the optional chain operator because it allows easy access to properties from nested objects. It prevents boilerplate code that validates null values on each property accessor in the visitor chain.
When the optional chain is used in conjunction with the null merge operator, you can get better results, making it easier to deal with default values.
At this point, I believe you have a deeper understanding of "what is the optional chain of JavaScript". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.