ES6 变量的解构赋值
解构赋值的用途
提取 JSON 数据
交换变量的值
let x = 1;
let y = 2;
[x, y] = [y, x];
从函数返回多个值
函数参数的定义
函数参数的默认值,但默认值生效的条件是值严格等于 undefined
遍历 Map 结构
任何部署了 Iterator 接口的对象,都可以用for...of循环遍历。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) {
// ...
}
输入模块的指定方法
const { SourceMapConsumer, SourceNode } = require("source-map");
1. 数组的解构赋值
// 1.完全解构
let [a, b, c] = [1, 2, 3];
// 2.不完全解构
let [x, y] = [1, 2, 3];
// 3. Set 结构的数组解构赋值
let [x, y, z] = new Set(['a', 'b', 'c']);
// 4.只要某种数据结构具有 Iterator 接口,都可以采用数组形式的解构赋值
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
// 5. 指定默认值,只有当一个数组成员严格等于 undefined,默认值才会生效,null 不严格等于 undefined
let [x, y = 'b', z = 1] = ['a', undefined, null]; // x='a', y='b',z='null'
// 6. 默认值可以引用解构赋值的其他变量,但该变量必须已经声明
let [x = 1, y = x] = []; // x=1; y=1
2. 对象的解构赋值
let { bar, foo } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"
let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"
foo // error: foo is not defined
// 默认值,生效的条件是,对象的属性值严格等于 undefined
var {x = 3} = {};
var { message: msg = 'Something went wrong' } = {};
// 数组本质是特殊的对象,因此可以对数组进行对象属性的解构
let arr = [1, 2, 3];
let {0 : first, [arr.length - 1] : last} = arr;
first // 1
last // 3
对象的解构赋值可以取到继承的属性
const obj1 = {};
const obj2 = { foo: 'bar' };
Object.setPrototypeOf(obj1, obj2);
const { foo } = obj1;
foo // "bar"
已经声明的变量用于解构赋值
// 正确的写法
let x;
({x} = {x: 1});
3. 字符串的解构赋值
const [a, b, c, d, e] = 'hello';
类似数组的对象都有一个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
5. 函数参数的解构赋值
function move({x = 0, y = 0} = {}) {
return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
圆括号问题
使用圆括号的情况只有一种:赋值语句的非模式部分,可以使用圆括号
[(b)] = [3]; // 正确
({ p: (d) } = {}); // 正确
[(parseInt.prop)] = [3]; // 正确
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论