美文网首页
解构赋值

解构赋值

作者: MJLUCY | 来源:发表于2019-12-18 20:47 被阅读0次

在ES5中,从对象和数组中获取特定数据并赋值给变量,有许多看起来同质化的代码

let options = {
    repeat: true,
    save: false
};
// 从对象中提取数据
let repeat = options.repeat,
save = options.save;

对象解构

let node = {
    type: "Identifier",
    name: "foo"
};
let { type, name } = node;
console.log(type); // "Identifier"
console.log(name); // "foo"

如果不是用在声明中,用在赋值中需要加小括号,因为语法规定,代码块语句不允许出现在赋值语句左侧。

let node = {
    type: "Identifier",
    name: "foo"
},
type = "Literal",
name = 5;
// 使用解构来分配不同的值
({ type, name } = node);
console.log(type); // "Identifier"
console.log(name); // "foo"

添加小括号后可以将块语句转化为一个表达式,从而实现整个解构赋值过程。
解构赋值表达式的值与表达式右侧(也就是=右侧)的值相等

let node = {
    type: "Identifier",
    name: "foo"
},
type = "Literal",
name = 5;
function outputInfo(value) {
    console.log(value === node); // true
}
outputInfo({ type, name } = node);
console.log(type); // "Identifier"
console.log(name); // "foo"

调用outputlnfo()函数时传入了一个解构表达式,由于JS表达式的值为右侧的值,因而此处传入的参数等同于node,且变量type和name被重新赋值,最终将node传入outputlnfo()函数

默认值

使用解构赋值表达式时,如果指定的局部变量名称在对象中不存在,那么这个局部变量会被赋值为undefined

let node = {
    type: "Identifier",
    name: "foo"
};
let { type, name, value } = node;
console.log(type); // "Identifier"
console.log(name); // "foo"
console.log(value); // undefined

当指定的属性不存在时,可以随意定义一个默认值,在属性名称后添加一个等号(=)和相应的默认值即可

let node = {
    type: "Identifier",
    name: "foo"
};
let { type, name, value = true } = node;
console.log(type); // "Identifier"
console.log(name); // "foo"
console.log(value); // true

在此示例中,为变量value设置了默认值true,只有当node上没有该属性或者该属性值为undefined时该值才生效。此处没有node.value属性,因为value使用了预设的默认值

为非同名局部变量赋值

let node = {
    type: "Identifier",
    name: "foo"
};
let { type: localType, name: localName } = node;
console.log(localType); // "Identifier"
console.log(localName); // "foo"

这段代码使用了解构赋值来声明变量localType和localName,这两个变量分别包含node.type和node.name属性的值。

嵌套对象解构

解构嵌套对象仍然与对象字面量的语法相似,可以将对象拆解以获取想要的信息

let node = {
    type: "Identifier",
    name: "foo",
    loc: {
        start: {
            line: 1,
            column: 1
        },
    end: {
        line: 1,
        column: 4
    }
}
};
let { loc: { start }} = node;
console.log(start.line); // 1
console.log(start.column); // 1

数组解构

let colors = [ "red", "green", "blue" ];
let [ firstColor, secondColor ] = colors;
console.log(firstColor); // "red"
console.log(secondColor); // "green"

也可以直接省略元素,只为感兴趣的元素提供变量名

let colors = [ "red", "green", "blue" ];
let [ , , thirdColor ] = colors;
console.log(thirdColor); // "blue"

用于直接赋值时,不需要加小括号

let colors = [ "red", "green", "blue" ],
firstColor = "black",
secondColor = "purple";
[ firstColor, secondColor ] = colors;
console.log(firstColor); // "red"
console.log(secondColor); // "green"

变量交换

可以用数组解构的方法很方便的实现变量交换

// 在 ES6 中互换值
let a = 1,
    b = 2;
[ a, b ] = [ b, a ];
console.log(a); // 2
console.log(b); // 1

默认值

也可以在数组解构赋值表达式中为数组中的任意位置添加默认值,当指定位置的属性不存在或其值为undefined时使用默认值

let colors = [ "red" ];
let [ firstColor, secondColor = "green" ] = colors;
console.log(firstColor); // "red"
console.log(secondColor); // "green"

嵌套数组解构

let colors = [ "red", [ "green", "lightgreen" ], "blue" ];
// 随后
let [ firstColor, [ secondColor ] ] = colors;
console.log(firstColor); // "red"
console.log(secondColor); // "green"

不定元素

在数组中,可以通过...语法将数组中的其余元素赋值给一个特定的变量

let colors = [ "red", "green", "blue" ];
let [ firstColor, ...restColors ] = colors;
console.log(firstColor); // "red"
console.log(restColors.length); // 2
console.log(restColors[0]); // "green"
console.log(restColors[1]); // "blue"
数组赋值

在ES5中,开发者们经常使用concat()方法来克隆数组

// 在 ES5 中克隆数组
var colors = [ "red", "green", "blue" ];
var clonedColors = colors.concat();
console.log(clonedColors); //"[red,green,blue]"

在ES6中,可以通过不定元素的语法来实现相同的目标

let colors = [ "red", "green", "blue" ];
let [ ...clonedColors ] = colors;
console.log(clonedColors); //"[red,green,blue]"

混合解构

let node = {
    type: "Identifier",
    name: "foo",
    loc: {
        start: {
            line: 1,
            column: 1
        },
        end: {
            line: 1,
            column: 4
        }
    },
    range: [0, 3]
};
let {
    loc: { start },
    range: [ startIndex ]
} = node;
console.log(start.line); // 1
console.log(start.column); // 1
console.log(startIndex); // 0

解构参数

普通写法

// options 上的属性表示附加参数
function setCookie(name, value, options) {
    options = options || {};
    let secure = options.secure,
        path = options.path,
        domain = options.domain,
        expires = options.expires;
        // 设置 cookie 的代码
}
// 第三个参数映射到 options
setCookie("type", "js", {
    secure: true,
    expires: 60000
});

使用解构参数

function setCookie(name, value, { secure, path, domain, expires }) {
// 设置 cookie 的代码
}
setCookie("type", "js", {
    secure: true,
    expires: 60000
});

解构参数需要使用对象或数组解构模式代替命名参数。如果调用函数时不提供被解构的参数会导致程序抛出错误。

// 出错!
setCookie("type", "js");

因为当调用setCookie()函数时,JS引擎实际上做了以下这些事情

function setCookie(name, value, options) {
    let { secure, path, domain, expires } = options;
    // 设置 cookie 的代码
}

如果解构赋值表达式的右值为null或undefined,则程序会报错。

如果解构参数是必需的,大可忽略掉这些问题;但如果希望将解构参数定义为可选的,那么就必须为其提供默认值来解决这个问题

function setCookie(name, value, { secure, path, domain, expires } = {}) {
    // ...
}

这个示例中为解构参数添加了一个新对象作为默认值,secure、path、domain及expires这些变量的值全部为undefined,这样即使在调用setCookie()时未传递第3个参数,程序也不会报错

默认值

function setCookie(name, value,
    {
        secure = false,
        path = "/",
        domain = "example.com",
        expires = new Date(Date.now() + 360000000)
    } = {}
) {
    // ...
}

将默认值放到setCookieDefaults对象中,在解构参数中可以直接使用这个对象来为每一个绑定设置默认参数。如果要改变默认值,可以立即在setCookieDefaults中修改,改变的数据将自动同步到所有出现过的地方。

其他解构

字符串解构

字符串也可以解构赋值。这是因为,字符串被转换成了一个类似数组的对象

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

类似数组的对象都有一个length属性,因此还可以对这个属性解构赋值

const {length} = 'hello';
console.log(length);//5

数值和布尔值解构

解构赋值时,如果等号右边是数值和布尔值,则会先转为对象

let {toString:s1} = 123;
console.log(s1 === Number.prototype.toString);//true
let {toString:s2} = true;
console.log(s2 === Boolean.prototype.toString);//true

解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。由于undefined和null无法转为对象,所以对它们进行解构赋值,都会报错

let { prop: x } = undefined; // TypeError
let { prop: y } = null; // TypeError

相关文章

网友评论

      本文标题:解构赋值

      本文链接:https://www.haomeiwen.com/subject/zciunctx.html