变量的赋值解构学习笔记

参考文章:http://es6.ruanyifeng.com/#docs/destructuring

数组的赋值结构

ES6 允许按照一定模式从数组和对象中提取值,然后对变量进行赋值,这被称为解构

完全解构

左边的和右边的一一对应,右边可以是数组和Set结构

let [a, b, c] = [1 ,2 ,3];
//或者
let [a, b, c] = new Set([1 ,2 ,3]);

解构不成功

解构失败

右边的不是数组或者Set结构,会直接失败

let [a] = 1;
let [b] = '1';
let [c] = true;
let [d] = undefined;
let [e] = null;
let [f] = {};

::: tip
要可以解构,右边的值转为对象后需要有Iterator接口
:::

不完全解构

如果可以解构,但是左边的值和右边的值不是一一对应的,没有对应的值将会被赋值为undefined

  • 左边少,右边多,会将前面的值一一对应,右边后面的值不会在管
let [a, b, c] = [1, 2, 3, 4, 5];
console.log(a); //1
console.log(b); //2
console.log(c); //3
  • 左边多,右边少,没有对应的值将会被赋值为undefined
let [a, b, c] = [1, 2];
console.log(a); //1
console.log(b); //2
console.log(c); //undefined

设置默认值

给左边的变量设置一个默认值

let [a, b = 1] = [1];
console.log(a, b); //a = 1 , b = 1

let [c, d = 1, e = 2, f = 3] = [1, 2, null, undefined];
console.log(c, d, e, f); //1 2 null 3

如果左边设置有默认值,那么在在右边相应的位置上的值判断是否===undefined

上面的例子可以理解为

let a, b = 1;
a = [1][0]; //a没有默认值,直接赋值
if ([1][1] === undefined) {
    // 什么都不做
} else {
    b = [1][1];
}
console.log(a, b);

let c, d = 1, e = 2, f = 3;

//c和d的省略

if ([1, 2, null, undefined][2] !== undefined) {
    e = [1, 2, null, undefined][2];
}
if ([1, 2, null, undefined][3] !== undefined) {
    f = [1, 2, null, undefined][3];
}
console.log(c, d, e, f);

对象的赋值解构

对象的赋值解构和数组的赋值解构规则差不多,但有一些差别

通过对象属性名取值

let {a, b} = {b: 2, a: 1};
console.log(a, b); //1 2

::: tip
其实上面的是一个简写,赋值解构的语法let {模式1: 变量1, 模式2: 变量2,...} = {模式1: 值1, 模式2: 值2,...};

let {a: a, b: b} = {b: 2, a: 1};

赋值的是后者,并不是前者
:::

例子

let node = {
    loc: {
        start: {
            line: 1,
            column: 5
        }
    }
};

let {loc, loc: { start }, loc: { start: {line}}} = node;
console.log(loc); //{ start: { line: 1, column: 5 } }
console.log(start); //{ line: 1, column: 5 }
console.log(line); //1
  • loc的赋值
//上面的式子等价于let {loc: loc, loc: { start }, loc: { start: {line}}} = node;
loc = node.loc;
  • start的赋值
//第一次赋值后
({ start } = node.loc);
//等价于({ start: start } = node.loc);
//第二次赋值
start = node.loc.start;
  • line的赋值
//第一次赋值后
({ start: {line}} = node.loc)
//第二次赋值
({line} = node.loc.start)
//等价于({line: line} = node.loc.start)
//第三次赋值
line = node.loc.start.line

字符串的赋值解构

字符串的赋值解构是可以把字符串转变为一个类似数组的对象

let [a, b, c, , d] = "hello world";
console.log(a, b, c, d); //h e l o

圆括号问题

不能使用圆括号

  • 变量声明语句

  • 函数参数

  • 赋值语句的模式

可以使用圆括号

  • 赋值语句的非模式部分可以使用圆括号

用途

  • 交换变量的值

  • 从函数返回多个值

  • 函数参数的定义

  • 提取JSON数据

  • 函数参数的默认值

  • 遍历Map结构

  • 输入模块的指定方法

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务