当前位置:网站首页>Deconstruction assignment of ES6 variables
Deconstruction assignment of ES6 variables
2022-07-28 09:08:00 【w ͏ l ͏ j ͏】
What is deconstruction assignment ?
ES6 Allow to follow certain mode , Extract values from arrays and objects , Assign values to variables , This is called deconstruction (Destructuring).
// MDN official
let a, b, rest;
[a, b] = [10, 20];
console.log(a);
// expected output: 10
console.log(b);
// expected output: 20
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(rest);
// expected output: Array [30,40,50]
Deconstruction and assignment of arrays
// Deconstructing success
let [a, b, c] = [1, 2, 3]; a 1,b 2,c 3
let [foo, [[bar], baz]] = [1, [[2,4], 3]]; // foo 1,bar 2,baz 3
let [ , , third] = ["foo", "bar", "baz"]; // third "baz"
let [head, ...tail] = [1, 2, 3, 4]; // head 1,tail [2,3,4]
// Deconstruction failure
let [foo] = []; // foo undefined
let [bar, foo] = [1]; // foo undefined
// As long as a data structure has Iterator Interface , Can be used as an array of deconstruction assignment . Conversely, deconstruction fails
// Report errors
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {
};
// Allow default values
let [a,b=2] = [1] // a = 1,b = 2
let [x = f()] = [1]; // The default value is expression , Expressions are lazy to evaluate , Only when used will it be evaluated .
// The default value can refer to other variables assigned by deconstruction , But the variable must have declared .
let [x = 1, y = x] = []; // x=1; y=1
Object's deconstruction assignment
// Array deconstruction depends on order , But object deconstruction depends on key, The following two are equivalent , The failure of deconstruction is undefined
let {
foo, bar } = {
foo: 'aaa', bar: 'bbb' };
let {
foo, bar } = {
bar: 'bbb', foo: 'aaa' };
// Deconstruction of nested objects
let obj = {
p: [
'Hello',
{
y: 'World' }
]
};
let {
p, p: [x, {
y }] } = obj;
x // "Hello"
y // "World"
p // ["Hello", {y: "World"}]
const node = {
loc: {
start: {
line: 1,
column: 5
}
}
};
let {
loc, loc: {
start }, loc: {
start: {
line }} } = node;
line // 1
loc // Object {start: Object}
start // Object {line: 1, column: 5}
Deconstruction and assignment of strings
const [a, b, c, d, e] = 'hello';
Deconstruction of function parameters
function add([x, y]){
return x + y;
}
add([1, 2]); // 3
[[1, 2], [3, 4]].map(([a, b]) => a + b);
// [ 3, 7 ]
You can't use parentheses
// Variable declaration statements All reported wrong
let [(a)] = [1];
let {
x: (c)} = {
};
let ({
x: c}) = {
};
let {
(x: c)} = {
};
let {
(x): c} = {
};
let {
o: ({
p: p }) } = {
o: {
p: 2 } };
// Function parameter
// Report errors
function f([(z)]) {
return z; }
// Report errors
function f([z,(x)]) {
return x; }
// Assignment statement
({
p: a }) = {
p: 42 };
([a]) = [5];
// All in all , As long as there is the possibility of deconstructing ambiguity , Don't bring it ().
// The non modal part of the assignment statement , You can use parentheses .
[(b)] = [3]; // correct
({
p: (d) } = {
}); // correct
[(parseInt.prop)] = [3]; // correct
Deconstruction uses
// Exchange the values of variables similar python The grammar
let x = 1;
let y = 2;
[x, y] = [y, x];
// Return multiple values from function
// Returns an array
function example() {
return [1, 2, 3];
}
let [a, b, c] = example();
// Return an object
function example() {
return {
foo: 1,
bar: 2
};
}
let {
foo, bar } = example();
// Defining parameters
// Parameters are a set of ordered values
function f([x, y, z]) {
... }
f([1, 2, 3]);
// Parameter is a set of unordered values
function f({
x, y, z}) {
... }
f({
z: 3, y: 2, x: 1});
// extract JSON data
let jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let {
id, status, data: number } = jsonData;
// The default value of the function parameter
jQuery.ajax = function (url, {
async = true,
beforeSend = function () {
},
cache = true,
complete = function () {
},
crossDomain = false,
global = true,
// ... more config
} = {
}) {
// ... do stuff
};
// Traverse Map
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
// Specify the method of introducing the module
const {
SourceMapConsumer, SourceNode } = require("source-map");
import {
x,xx,xxx} from 'xx'
Reference resources :
- Mr. Ruan Yifeng 《ES6 Introduction to the standard The third edition 》
- MDN Destructuring assignment
边栏推荐
- Competition: diabetes genetic risk detection challenge (iFLYTEK)
- Principle of line of sight tracking and explanation of the paper
- 【单细胞高级绘图】07.KEGG富集结果展示
- Do you know the five minute rule and the ten byte rule?
- 49 opencv deep analysis profile
- Sentinel
- Learn to draw with nature communications -- complex violin drawing
- Introduction to official account
- After reading these 12 interview questions, the new media operation post is yours
- JSON file storage
猜你喜欢
![[advanced drawing of single cell] 07. Display of KEGG enrichment results](/img/77/0a9006743734c1993785d087f957f0.png)
[advanced drawing of single cell] 07. Display of KEGG enrichment results

Introduction of functions in C language (blood Book 20000 words!!!)

C language array pointer and pointer array discrimination, analysis of memory leakage

Data analysis interview question summary

c语言数组指针和指针数组辨析,浅析内存泄漏

网络层的IP协议

Why is the text box of Google material design not used?

No one wants to tell the truth about kubernetes secret

Among China's top ten national snacks, it is actually the first

Network interface network crystal head RJ45, Poe interface definition line sequence
随机推荐
Different HR labels
After summarizing more than 800 kubectl aliases, I'm no longer afraid that I can't remember commands!
Mongodb (compare relational database, cloud database, common command line, tutorial)
Code management platform SVN deployment practice
Go panic and recover
C language array pointer and pointer array discrimination, analysis of memory leakage
Principle of line of sight tracking and explanation of the paper
A perfect cross compilation environment records the shell scripts generated by PETA
Learn to draw with nature communications -- complex violin drawing
Sword finger offer
The chess robot pinched the finger of a 7-year-old boy, and the pot of a software testing engineer? I smiled.
台大林轩田《机器学习基石》习题解答和代码实现 | 【你值得拥有】
C #, introductory tutorial -- debugging skills and logical error probe technology and source code when the program is running
Detailed explanation of switch link aggregation [Huawei ENSP]
Will sqlserver CDC 2.2 generate table locks when extracting large tables from the source
实现批量数据增强 | keras ImageDataGenerator使用
Setting of parameter configuration tool for wireless vibrating wire collector
修改虚拟机IP地址
Let me teach you how to assemble a registration center?
leetcode 452. Minimum Number of Arrows to Burst Balloons 用最少数量的箭引爆气球(中等)