3
3
// Destructuring es una técnica rápida para asignar propiedades de objetos a
4
4
// variables, o items de un array a variables.
5
5
6
-
7
6
// "DESTRUCTURING" SOBRE OBJETOS
8
7
9
8
// Ejemplo a mano, sin "destructuring":
@@ -74,23 +73,22 @@ const student = {
74
73
country : "USA" ,
75
74
} ;
76
75
const getName = ( { name } ) => name ;
77
- console . log ( getName ( student ) ) ; // "Evan"
78
-
76
+ console . log ( getName ( student ) ) ; // "Evan"
79
77
80
78
// "DESTRUCTURING" SOBRE ARRAYS
81
79
82
80
// Ejemplo a mano, sin "destructuring":
83
81
const students = [ "Alan" , "Evan" , "Ana" ] ;
84
- const alan = students [ 0 ] ;
85
- const evan = students [ 1 ] ;
86
- const ana = students [ 2 ] ;
87
- const nobody = students [ 3 ] ;
88
- console . log ( alan ) ; // "Alan"
89
- console . log ( evan ) ; // "Evan"
90
- console . log ( ana ) ; // "Ana"
91
- console . log ( nobody ) ; // undefined
92
-
93
- // Pero con "destructuring" podemos asignar elementos existentes en
82
+ const first = students [ 0 ] ;
83
+ const second = students [ 1 ] ;
84
+ const third = students [ 2 ] ;
85
+ const fourth = students [ 3 ] ;
86
+ console . log ( first ) ; // "Alan"
87
+ console . log ( second ) ; // "Evan"
88
+ console . log ( third ) ; // "Ana"
89
+ console . log ( fourth ) ; // undefined
90
+
91
+ // Pero con "destructuring" podemos asignar elementos existentes en
94
92
// el array a variables de forma directa, en una línea:
95
93
// [!] El orden en la asignación se mantiene
96
94
const students = [ "Alan" , "Evan" , "Ana" ] ;
@@ -109,20 +107,19 @@ console.log(third); // "Ana"
109
107
// argumento de una función:
110
108
const students = [ "Alan" , "Evan" , "Ana" ] ;
111
109
const getSecond = ( [ , second ] ) => second ;
112
- console . log ( getSecond ( students ) ) ; // "Evan"
110
+ console . log ( getSecond ( students ) ) ; // "Evan"
113
111
114
112
// También se puede aplicar "destructuring" profundo en
115
113
// arrays bidimensionales.
116
114
const matrix = [
117
115
[ 0 , 0 , 0 ] ,
118
116
[ 0 , 10 , 0 ] ,
119
- [ 0 , 0 , 0 ]
117
+ [ 0 , 0 , 0 ] ,
120
118
] ;
121
119
122
120
const [ , [ , center ] ] = matrix ;
123
121
console . log ( center ) ; // 10;
124
122
125
-
126
123
// "DESTRUCTURING" PARA REASIGNAR VARIABLES
127
124
128
125
// Se pueden hacer cosas bastante bizarras con el destructuring, como
@@ -145,3 +142,6 @@ console.log(b);
145
142
146
143
console . log ( a ) ;
147
144
console . log ( b ) ;
145
+
146
+ // El equivalente con destructuring de objetos podría ser:
147
+ ( { a : b , b : a } = { a, b } ) ;
0 commit comments