一. 基本用法
定义:ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构
1.1 没有对应值的变量会当作undefied处理 如果是数组的化 会被当做空数组[]
let [x, y, ...z] = [‘a‘]; // x"a" y undefined z [] let [x, y, ...z] = [‘a‘,,‘x‘,‘z‘]; // x "a" y undefined z [‘x‘,‘z‘]
1.2 结构赋值允许指定默认值
let [x, y = ‘b‘,z=[‘1‘]] = [‘a‘, undefined]; // x=‘a‘, y=‘b z=[‘1‘]
二.对象的解构
1. let { foo: baz } = { foo: ‘aaa‘, bar: ‘bbb‘ };baz // "aaa 2. let obj = { first: ‘hello‘, last: ‘world‘ }; let { first: f, last: l } = obj;//f ‘hello‘ l ‘world‘ 3. const node = { loc: { start: { line: 1, column: 5 } } }; let { loc:{ start: { line:test, column:test2 }}} = node; // test = 1, test2 = 5, node = Object{loc:Object} 4.let arr = [1, 2, 3]; let {0 : first, [arr.length - 1] : last} = arr; // first// 1 last// 3
三 字符串的解构赋值
const [a, b, c, d, e] = ‘hello‘;//a // "h" b // "e" c // "l" d // "l" e // "o" let {length : len} = ‘hello‘; //len // 5
四 数值和布尔值的解构赋值
解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。由于undefined和null无法转为对象,所以对它们进行解构赋值,都会报错。
五 函数的参数解构赋值
[[1, 2], [3, 4]].map(([a, b]) => a + b);// [ 3, 7 ] function add([x, y]){return x + y;}add([1, 2]); // 3
六 用途
(1)交换变量的值
let x = 1; let y = 2; [x, y] = [y, x];
(2)从函数返回多个值
// 返回一个数组 function example() { return [1, 2, 3]; } let [a, b, c] = example(); // 返回一个对象 function example() { return { foo: 1, bar: 2 }; } let { foo, bar } = example();
(3)函数参数的定义
// 参数是一组有次序的值
function f([x, y, z]) { ... } f([1, 2, 3]);
// 参数是一组无次序的值
function f({x, y, z}) { ... } f({z: 3, y: 2, x: 1});
(4)提取 JSON 数据
let jsonData = { id: 42, status: "OK", data: [867, 5309] }; let { id, status, data: number } = jsonData; console.log(id, status, number);// 42, "OK", [867, 5309]
(5)遍历 Map 结构
// 获取键名 for (let [key] of map) { // ... } // 获取键值 for (let [key,value] of map) { // ... }
(6)输入模块的指定方法
const { SourceMapConsumer, SourceNode } = require("source-map");
原文:https://www.cnblogs.com/dwzheng/p/10393058.html