ES6中的解构:按照一定模式,从数组和对象中提取值,对变量进行赋值
数组的元素按照次序排列,变量取值按照位置决定;对象的属性没有次序,变量必须与属性同名,才能取到正确的值。
1.数组的结构赋值
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]
let [x, y, ...z] = ['a'];
x // "a"
y // undefined 如果解构不成功,则等于 undefined
z // []
-----------------------------------------------------
不完全解构
let [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4
----------------------------------------------------
等号右边不是数组则报错
let[foo] = 1; //报错
let[foo] = false; //报错
---------------------------------------------------
对于Set结构,可以使用数组的解构赋值
let [foo = true] = [];
foo // true
let [x, y, z] = new Set(['a', 'b', 'c']);
x // "a"
--------------------------------------------------
默认值
let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'
只有当一个数组成员严格等于 undefined ,默认值才会生效。
let [x = 1] = [undefined];
x // 1
let [x = 1] = [null];
x // null
默认值可以引用解构赋值的其他变量,但是该变量必须已经声明。
let[x = 1,y = x] = []; //x = 1, y = 1
let[x = 1,y = x] = [2]; //x = 2, y = 2
let[x = 1,y = x] = [2,3]; //x = 2,y = 3
let[y = x,x = 1] = []; //报错,y还没有声明
2.对象的解构赋值
let { foo, bar } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"
没有对应的同名属性,则返回 undefined
let {foo} = {bar: 'baz'};
foo // undefined
可以方便地将现有对象的方法,赋值到某个变量。
let{ log, sin, cos } = Math; //将Math 对象的对数、正弦、余弦赋值到对应的变量上
const { log } = console;
log('hello') //hello //将console.log赋值到log变量
如果变量名与属性名不一致,必须写成下面这样。
let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"
let obj = { first: 'hello', last: 'world' };
let { first: f, last: l } = obj;
f // 'hello'
l // 'world'
对象的解构赋值的内部机制,是先找到同名属性,然后再赋给对应的变量。真正赋值的是后者,而不是前者。
let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"
foo // error: foo is not defined
解构可以用于嵌套结构的对象。
let obj = {
p: [
'Hello',
{ y: 'World' }
]
};
let { p: [x, { y }] } = obj;
x // "Hello"
y // "World"
如果想要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}
//分别对loc 、 start 、line 三个属性的解构赋值。
//最后一次对line属性的解构赋值中,只有line是变量, loc和start都是模式,不是变量
嵌套赋值的例子:
下面是嵌套赋值的例子。
let obj = {};
let arr = [];
({ foo: obj.prop, bar: arr[0] } = { foo: 123, bar: true });
obj // {prop:123}
arr // [true]
对象的解构赋值可以取到继承的属性:
const obj1 = {};
const obj2 = { foo: 'bar' };
Object.setPrototypeOf(obj1, obj2);
const { foo } = obj1;
foo // "bar"
//对象obj1的原型对象是obj2,foo属性不会obj1自身的属性,而是继承自obj2的属性。
------------------------------------------------------------------------------
默认值:生效条件,对象的属性值严格等于undefined
举例:
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"
var {x = 3} = {x: undefined};
x // 3
var {x = 3} = {x: null};
x // null 因为null与undefined不严格相等,所以是个有效的赋值,导致默认值3不会生效
注意事项:
(1)如果要将一个已经声明的变量用于解构赋值,必须非常小心
// 错误的写法
let x;
{x} = {x: 1};
// SyntaxError: syntax error
//{x} 理解成一个代码块,从而发生语法错误
// 正确的写法
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"
类似数组的对象有一个length属性,因此可以对这个属性解构赋值:
let {length : len } = 'hello';
len // 5
4.数组和布尔值的解构赋值 : 如果等号右边是数值和布尔值,则会先转为对象。
let {toString: s} = 123;
s === Number.prototype.toString // true
let {toString: s} = true;
s === Boolean.prototype.toString // true
等号右边不是对象或是数组,就先将其转为对象,如果是undefined和null,则会报错。
let { prop : x } = undefined; //报错
let { prop : y } = null; //报错
5.函数参数的解构赋值
例1:
function add([x, y]){
return x + y;
}
add([1, 2]); // 3
例2:
[[1, 2], [3, 4]].map(([a, b]) => a + b);
// [ 3, 7 ]
默认值:
例1:
function move({x = 0, y = 0} = {}) {
return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, 0]
move({}); // [0, 0]
move(); // [0, 0]
例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]
例3:
[1, undefined, 3].map((x = 'yes') => x);
// [ 1, 'yes', 3 ]
6.圆括号问题
不使用圆括号的情况:
(1)变量声明语句
// 全部报错
let [(a)] = [1];
let {x: (c)} = {};
let ({x: c}) = {};
let {(x: c)} = {};
let {(x): c} = {};
let { o: ({ p: p }) } = { o: { p: 2 } };
(2)函数参数
// 报错
function f([(z)]) { return z; }
// 报错
function f([z,(x)]) { return x; }
(3)赋值语句的模式
// 全部报错
({ p: a }) = { p: 42 };
([a]) = [5];
// 报错
[({ p: a }), { x: c }] = [{}, {}];
可以使用圆括号的情况:赋值语句的非模式部分
[(b)] = [3]; // 正确
({ p: (d) } = {}); // 正确
[(parseInt.prop)] = [3]; // 正确
7.用途
(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)函数参数的默认值
jQuery.ajax = function (url, {
async = true,
beforeSend = function () {},
cache = true,
complete = function () {},
crossDomain = false,
global = true,
// ... more config
} = {}) {
// ... do stuff
};
(6)遍历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
// 获取键名
for (let [key] of map) {
// ...
}
// 获取键值
for (let [,value] of map) {
// ...
}
(7)输入模块的指定方法:加载模块,往往需要输入哪些方法。
const { SourceMapConsumer, SourceNode } = require("source-map");
|