ES6 allows to extract values from arrays and objects and assign values to variables according to a certain pattern, which is called destructuring.
Array destructuring and assignment
The elements of an array are arranged in order, and the value of a variable is determined by its position!
Originally, extracting values from the array to assign values to variables requires this:
var arr = [1,3,5];
var a = arr[0];
var b = arr[1];
var c = arr[2];
Now:
var arr = [1,3,5];
let[a,b,c] = arr;
let[head,...tail] = arr;
//head 1 tail [3,5]
let[n,m] = arr;//1 3
let[x,y,z,p] = arr//1 3 5 undefined
Object destructuring assignment
The properties of an object have no order, and the variable must have the same name as the property to get the correct value!
let obj = {name:'scy', age:18};
let {age, name} = obj;//age 18 name 'scy'
let {baz} = obj;//undefined
let {tt,name,ss} = obj;//undefined 'scy' undefined
String destructuring
Strings can also be destructed, and are converted into array-like objects during destructuring!
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
Array-like objects all have a length property, so you can also destruct and assign to this property.
let {length} = "abc";
console.log(length);//3
var arr = [1,3,5];
let {length} = "abc";//3
The purpose of
destructuring Destructuring provides an extremely concise assignment method, and has many uses, such as:
the extraction of JSON data returned in the background
let json= {
ret: 0,
msg: "OK",
data: {
id:111,
name:"scy"
}
}
let {ret,msg,data} = json;//0, 'OK', { id: 111, name: 'scy' }
Swap of variables without resorting to other variables
let x = 1;
let y = 2;
[x, y] = [y, x];
Traverse the Map structure
const map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
for (let [key, value] of map) {
console.log(key + " is " + value);
}
// first is hello
// second is world
module import
import {
Platform,
StyleSheet,
Text,
View
} from 'react-native';
Another example is the deconstruction of attributes in RN and const { name } = this.props;
so on!
Refer to Getting Started with ECMAScript 6