二、遍历的解构赋值
1. 数组的解构赋值
基本用法
ES6解构:按照一定模式便捷的从对象和数组中提取/赋值
- 便捷性说明
前(ES5)
let a = 1;
let b = 2;
let c = 3;
后(ES6)
let [a, b, c] = [1, 2, 3];
- 常用情况
嵌套数组赋值
let [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3
间隔赋值
let [ , , third] = ["foo", "bar", "baz"];
third // "baz"
间隔赋值
let [x, , y] = [1, 2, 3];
x // 1
y // 3
...赋值
let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]
不完全解构,失败部分为undefined或[]
let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z // []
- 不合法情况
如果右边不是数组或者说Iterator可遍历结构则报错
// 报错
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};
- 进一步说明?
只要右边赋值的数据结构具有Iterator接口即可进行解构赋值。
Generator函数
function* fibs() {
let a = 0;
let b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
let [first, second, third, fourth, fifth, sixth] = fibs();
sixth // 5
默认值
- 解构赋值允许指定默认值
let [foo = true] = [];
foo // true
let [x, y = 'b'] = ['a']; // x='a', y='b'
let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'
- 当赋值undefined才会生效(ES6使用的是===,所以null则默认值不生效)
let [x = 1] = [undefined];
x // 1
let [x = 1] = [null];
x // null
- 默认值如是表达式,则在使用时才会用到(非undefined)
function f() {
console.log('aaa');
}
let [x = f()] = [1];
//x=1
- 避免暂时性死区
let [x = 1, y = x] = []; // x=1; y=1
let [x = 1, y = x] = [2]; // x=2; y=2
let [x = 1, y = x] = [1, 2]; // x=1; y=2
let [x = y, y = 1] = []; // ReferenceError: y is not defined
2. 对象的解构赋值
基本用法
- 便捷性说明
// 例一
let { log, sin, cos } = Math;
// 例二
const { log } = console;
log('hello') // hello
- 数组与对象解构的区别
(1)数组是按次序排列进行解构
(2)对象是对应属性名进行解构
let { bar, foo } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"
let { baz } = { foo: 'aaa', bar: 'bbb' };
baz // undefined
- 对象&数组解构失败都是undefined
let {foo} = {bar: 'baz'};
foo // undefined
- 对象解构赋值与数组不同
先找到同名属性,再赋给对应的变量——真正被赋值的是后者,而不是前者。
对象的解构赋值:
let { foo: foo, bar: bar } = { foo: 'aaa', bar: 'bbb' };
let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"
foo // error: foo is not defined
- 与数组同样适用嵌套的对象
(1)p作为模式不会被赋值
let obj = {
p: [
'Hello',
{ y: 'World' }
]
};
let { p: [x, { y }] } = obj;
x // "Hello"
y // "World"
(2)p作为变量赋值
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}
- 避免暂时性死区
// 报错,foo不存在undefined
let {foo: {bar}} = {baz: 'baz'};
- 继承的属性一样可以解构赋值
const obj1 = {};
const obj2 = { foo: 'bar' };
Object.setPrototypeOf(obj1, obj2);
const { foo } = obj1;
foo // "bar"
默认值
- 解构赋值指定默认值
var {x = 3} = {};
x // 3
var {x, y = 5} = {x: 1};
x // 1
y // 5
var {x: y = 3} = {};
y // 3
var {x: y = 3} = {x: 5};
y // 5
var { message: msg = 'Something went wrong' } = {};
msg // "Something went wrong"
- 只有解构对象的属性值为undefined才生效(同数组)
var {x = 3} = {x: undefined};
x // 3
var {x = 3} = {x: null};
x // null
- 特殊情况
(1)对已声明的对象进行解构,需使用()进行赋值,否则会被理解成代码块
// 错误的写法
let x;
{x} = {x: 1};
// SyntaxError: syntax error
// 正确的写法
let x;
({x} = {x: 1});
(2)无意义。解构赋值允许等号左边模式之中不放置任何变量名
({} = [true, false]);
({} = 'abc');
({} = []);
(3)对数组进行对象解构(数组是特殊的对象)
let arr = [1, 2, 3];
let {0 : first, [arr.length - 1] : last} = arr;
first // 1
last // 3
3. 字符串的解构赋值
字符串可以解构赋值,是因为字符串被转换成一个类似数组的对象。同时可就数组类型进行属性解构。
- 实例说明
取元素赋值解构
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
//取属性值解构
let {length : len} = 'hello';
len // 5
4. 数值和布尔值的解构赋值
解构赋值时
(1)如果有变是数值或布尔值则会转为对象
(2)如果是undefined和null则无法转为对象
- 实例说明
(1)变量s赋值为123/true转换后的对象的toString属性。
let {toString: s} = 123;
s === Number.prototype.toString // true
let {toString: s} = true;
s === Boolean.prototype.toString // true
(2)
let { prop: x } = undefined; // TypeError
let { prop: y } = null; // TypeError
5. 函数参数的解构赋值
参数数组/对象相对(1)直接进行解构赋值(2)可使用默认值(undefined也触发)
(1)数组对数组
function add([x, y]){
return x + y;
}
add([1, 2]); // 3
(2)对象对对象,同时使用默认值
function move({x, y} = { x: 0, y: 0 }) {
return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, undefined]
move({}); // [undefined, undefined]
move(); // [0, 0]
6. 圆括号问题
对于编译器来说,一个式子是模式还是表达式并不明了,到解析才知道。带来的问题是
(1)ES6可能导致解构的歧义
不能使用圆括号的情况
- 变量声明语句(模式),不能使用圆括号
// 全部报错
let [(a)] = [1];
let {x: (c)} = {};
let ({x: c}) = {};
let {(x: c)} = {};
let {(x): c} = {};
let { o: ({ p: p }) } = { o: { p: 2 } };
- 函数参数(也属于变量声明)
// 报错
function f([(z)]) { return z; }
// 报错
function f([z,(x)]) { return x; }
- 赋值的模式
// 报错
[({ p: a }), { x: c }] = [{}, {}];
可以使用圆括号的情况
与不可使用相反。非模式即表达式,则可使用圆括号
- 例子
[(b)] = [3]; // 正确
({ p: (d) } = {}); // 正确
[(parseInt.prop)] = [3]; // 正确
7. 用途
- 交换变量的值
let x = 1;
let y = 2;
[x, y] = [y, x];
- 从函数返回多个值
// 返回一个数组
function example() {
return [1, 2, 3];
}
let [a, b, c] = example();
// 返回一个对象
function example() {
return {
foo: 1,
bar: 2
};
}
let { foo, bar } = example();
- 函数参数的定义
// 参数是一组有次序的值
function f([x, y, z]) { ... }
f([1, 2, 3]);
// 参数是一组无次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});
- 提取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]
- 函数参数的默认值
jQuery.ajax = function (url, {
async = true,
beforeSend = function () {},
cache = true,
complete = function () {},
crossDomain = false,
global = true,
// ... more config
} = {}) {
// ... do stuff
};
- 遍历Map结构(Map原生结构支持Iterator接口)
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
// 获取键名
for (let [key] of map) {
// ...
}
// 获取键值
for (let [,value] of map) {
// ...
}
Object和map区别只在于键的类型,前者字符串,后者可以是任何类型
- 输入模块的指定方法
const { SourceMapConsumer, SourceNode } = require("source-map");