In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces how to deconstruct arrays and objects in Javascript, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
Define
There is no more concise definition of deconstructing assignments than MDN:
The deconstructing assignment syntax is an JavaScript expression that unwraps values in an array or attributes in an object into different variables. Array deconstruction We use square brackets: [] to deconstruct the array.
Let's look at the different scenarios where we can deconstruct the assignment, consider an array of three elements, and now you want to create three different variables with the values in the array. The old method was to use the index to assign values in the array to each new variable.
Const arr = [1,2,3]; const a = arr [0]; / a = 1const b = arr [1]; / b = 2const c = arr [2]; / c = 3
However, using deconstruction assignments can greatly reduce the amount of work required to perform the same task.
Const arr = [1,2,3]; const [a, b, c] = arr;// a = 1, b = 2, c = 3 Note: the original array is unaffected and remains intact. Only assignment occurs from left to right.
If we only need two elements in the array, we can use the same syntax for both variables. The remaining values of more than two elements in the array are discarded.
We can also skip the intermediate element using the space of the element in the array as needed. Refer to the example for a better understanding of:
Const arr = [1,2,3,4]; / a = 1, b = 2const [a, b] = arr;// x = 2, y = 4const [, x, y] = arr; uses deconstruction exchange values
Traditionally, we can use temporary variables to explicitly exchange values, and then assign and reassign values between three variables, but now we can use deconstruction to assign values directly, as shown in the following example:
Let a = 10, b = 20 temp; / Old waylet temp = a * a = b * b = b * b / / a = 20, b = 10 *
Let's consider an object restaurant with few properties:
Const restaurant = {name:'La\ 'Pinoz Pizza', location:' Ghaziabad', categories: ['Italian',' Vegetarian', 'Non-Vegetarian',' Organic'], starterMenu: ['Garlic Bread',' Fries', 'Pastries'], mainMenu: [' Pizza', 'Pasta',' Risotto'], order: function (starterIndex, mainIndex) {return [this.starterMenu [starterIndex], this.mainMenu [mainIndex]] }}
The order property of the restaurant object is a function that takes two parameters and returns an array of two values. We can use deconstruction here to assign elements of Array directly to variables.
Const [starter, mainCourse] = restaurant.order (2jue 1); console.log (starter, mainCourse); / / output: Pastries Pasta nesting deconstruction
As the name implies, it is very simple to deconstruct an array in an array. Consider an array with nested arrays: [1,2, [3,4]]. When we use this array to assign the value of a ~, everyone will get a single element assigned, that is, a = 1, b = 2, c = [3 ~ 4]. If we want to separate the value from the array c, we can use a similar deconstruction syntax and implement it.
Const nested = [1,2, [3,4]]; const [a, b, c] = nested; / / a = 1, b = 2, c = [3,4] const [x, [y, z]] = nested; / / x = 1, y = 3, z = 4 default value
If we don't know the data contained in the incoming array, the default value assigned to the variable is undefined. Let's look at an example and understand:
Const unknownArray = [1, 5, 9]; const [a recalcitrance brecinct crecedence d] = unknownArray;console.log (a recalcitrance brecory c pencil d); / / Output: 159 undefined object deconstruction We use curly braces: {} to deconstruct the object. We must provide a variable name that exactly matches the property name in the object. (although we'll also see a way to use different variable names).
Let's consider a restaurant object similar to the one above, with more properties:
Const restaurant = {nameOfRestaurant:'La\ 'Pinoz Pizza', location:' Ghaziabad', categories: ['Italian',' Vegetarian', 'Non-Vegetarian',' Organic'], starterMenu: ['Garlic Bread',' Fries', 'Pastries'], mainMenu: [' Pizza', 'Pasta',' Risotto'], order: function (starterIndex, mainIndex) {return [this.starterMenu [starterIndex], this.mainMenu [mainIndex]] }, openingHours: {thu: {open: 11, close: 22}, fri: {open: 10, close: 23}, sat: {open: 11, close: 23}
We can deconstruct the restaurant object with its property name, and now the order of the attributes doesn't matter, because it can be accessed as long as the attribute names match.
Const {nameOfRestaurant, openingHours, mainMenu} = restaurant;console.log ('Name:', nameOfRestaurant); console.log ('Opening Hours:', openingHours); console.log ('Main Menu:', mainMenu) / / Output:// Name: La' Pinoz Pizza// Opening Hours: {open: 11, close: 22}, / / fri: {open: 10, close: 23}, / / sat: {open: 11, close: 23} / / Main Menu: ['Pizza',' Pasta', 'Risotto'] use different variable names
Even if we want to change the variable name that is different from the attribute name, we still need to know the attribute name in advance. So it's always a good habit to find incoming objects. Okay, so we can use the colon (:) to specify an alias for the attribute name.
Const {nameOfRestaurant: name, openingHours: timing, mainMenu: menu} = restaurant;console.log ('Name:', name); console.log ('Opening Hours:', timing); console.log ('Main Menu:', menu); / / We get the output similar to the above output. Set default value
We can always assign a default value to a variable when deconstructing an object. If the value exists in the object, it is assigned to the variable; if it does not, the default value is assigned to the variable.
Const {nameOfRestaurant: name = 'PizzaHut', menu = []} = restaurant;// Lets assume that the restaurant object has no property with name' nameOfRestaurant', / / In this case the name becomes' PizzaHut'. / / On the other hand there is no menu property so menu is assigned with empty array. Variation value
We should be careful with curly braces when using object deconstruction to change values, because javascript expects a block of code as soon as it encounters open curly braces.
To solve this situation, we wrap the deconstruction code in parentheses. Let a = 11 b = 23 = {a: 120, b: 34}; ({a, b} = obj); / / Important lineconsole.log (a, b) / / a = 120,b = 34 Thank you for reading this article carefully. I hope the article "how to deconstruct arrays and objects in Javascript" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you 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.