Tips:对象解构、数组解构
解构是一种打破数据解构,将其拆分为更小部分的过程。
为何使用解构功能
在 ES5 之前,开发者为了从对象和数组中获得特定数据并赋值给变量,编写了许多看起来同质化的代码:
let options = {
repeat: true,
save: false
};
// 从对象中提取数据
let repeat = options.repeat,
save = options.save;
对象解构
对象解构的语法形式是:在一个赋值操作符左边放置一个对象字面量。
💡 语法类似于 Swift 语法中的元组(Tuple)。
let node = {
type: 'Identifier',
name: 'foo'
};
// 变量声明中使用解构语法
let { type, name } = node;
console.log(type); // Identifier
console.log(name); // foo
Node.js 中经常会出现这样的代码:
async functionName(param) {
const { ctx, service } = this;
// 实际上:
// ctx = this.ctx
// service = this.service
}
解构赋值
给变量赋值时使用解构语法。
一定要用一对小括号包裹解构赋值语句:JS语法规定,代码块语句不允许出现在赋值语句左侧,添加小括号可以将代码块语句转化为一个表达式,从而实现整个解构赋值的过程。
let node = {
type: 'Identifier',
name: 'foo'
},
type = 'Literal',
name = 5;
// 使用解构语法为多个变量赋值
// 定义变量后修改变量的值
({ type, name } = node);
console.log(type); // Identifier
console.log(name); // foo
默认值
- 使用解构赋值表达式时,如果指定的局部变量名称在对象中不存在,那么这个局部变量会被赋值为
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
为非同名局部变量赋值
💡 语法类似于 Swift 语法中的函数参数标签,但是声明的顺序颠倒了。
let node = {
type: 'Identifier',
name: 'foo'
};
// let localType = node.type;
// let localName = node.name;
// type: localType 含义:读取名为 type 的属性,并将其值存储在变量 localType 中。
// name: localName = "bar",支持添加默认值
let { type: localType, name: localName = "bar" } = node;
console.log(localType); // Identifier
console.log(localName); // foo
嵌套对象解构
解构嵌套对象与对象字面量语法相似,可以将对象拆解以获取你想要的信息。
let node = {
type: 'Identifier',
name: 'foo',
loc: {
start: {
line: 1,
clumn: 1
},
end: {
line: 1,
clumn: 1
}
}
};
// let start = node.loc.start;
let { loc: { start }} = node;
console.log(start.line); // 1
console.log(start.clumn); // 1
// 支持使用与对象属性名不同的局部变量名(另外设置一个变量名)
let { loc: { start: localStart }} = node;
console.log(localStart.line); // 1
console.log(localStart.clumn); // 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 = "green"] = colors;
console.log(firstColor); // red
console.log(secondColor); // green
数组解构语法的独特用例:交换两个变量的值。
// 在 ECMAScript 5 中交换变量
let a = 1,
b = 2,
tmp;
tmp = a;
a = b;
b = tmp;
console.log(a); // 2
console.log(b); // 1
// -------------------------
// 在 ECMAScript 6 中交换变量
let a = 1,
b = 2;
[a, b] = [b, a];
console.log(a); // 2
console.log(b); // 1
嵌套数组解构
let colors = ["red", ["green", "lightGreen"], "blue"];
// 变量 secondColor 引用的是 colors 数组中的值 "green"
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
在 ECMAScript 5 中,开发者经常使用 concat()
方法来克隆数组:
var colors = ['red', 'green', 'blue'];
// 在 ECMAScript 5 中克隆数组
var clonedColors = colors.concat();
console.log(clonedColors); // [ 'red', 'green', 'blue' ]
// 在 ECMAScript 6 中可以使用不定参数实现相同的功能
let [...clonedColors2] = colors;
console.log(clonedColors2); // [ 'red', 'green', 'blue' ]
混合解构
可以混合使用对象解构和数组解构来创建更多复杂的表达式。
let node = {
type: 'Identifier',
name: 'foo',
loc: {
start: {
line: 1,
column: 1
},
end: {
line: 1,
column: 1
}
},
range: [0, 3]
};
// 对象解构:start = node.local.start
// 数组解构:startIndex = node.range[0]
let {
loc: { start },
range: [startIndex]
} = node;
console.log(start.line); // 1
console.log(start.column); // 1
console.log(startIndex); // 0
解构参数
解构可以用在函数的参数传递过程中,当定义一个接受大量可选参数的 JavaScript 函数时,我们通常会创建一个可选对象,将额外的参数定义为这个对象的属性:
// name 和 value 是必需参数。
// secure、path、domain、expires 是可选参数
// options 的属性表示其他参数
function setCookie(name, value, options) {
options = options || {};
let secure = options.secure,
path = options.path,
domain = options.domain,
expires = options.expires;
// 设置 cookie 代码
}
// 第三个参数映射到 optoins 中
setCookie("type", "js", {
secure: true,
expires: 60000
});
以上的问题是,仅查看函数的声明,无法辨识函数的预期参数,必须阅读函数体才可以确定所有参数的情况。
将 options
定义为解构参数可以解决以上问题:
function setCookie(name, value, { secure, path, domain, expires }) {
// 设置 cookie 代码
}
setCookie('type', 'js', {
secure: true,
expires: 60000
});
必须传值的解构参数
解构参数有一个奇怪的地方:默认情况下,如果调用函数时不提供被解构的参数会导致程序抛出错误。
// 以上函数,不传解构参数会报错
setCookie('type', 'js'); // 报错!
解构参数的默认值
💡 对于对象类型的解构参数,建议为其赋予相同解构的默认参数。
// 第一个对象字面量是解构参数,第二个为默认值
function setCookie(name, value,
{
secure = false,
path = "/",
domain = "example.com",
expires = new Date(Date.now() + 360000000)
} = {
secure = false,
path = "/",
domain = "example.com",
expires = new Date(Date.now() + 360000000)
}
) {
// 设置 cookie 代码
}
优化:将默认值提取到一个独立对象中,以消除冗余:
// 将默认值设置为一个独立对象
const setCookieDefaults = {
secure = false,
path = "/",
domain = "example.com",
expires = new Date(Date.now() + 360000000)
}
function setCookie(name, value,
{
secure = false,
path = "/",
domain = "example.com",
expires = new Date(Date.now() + 360000000)
} = setCookieDefaults
) {
// 设置 cookie 代码
}