4 回答

TA贡献1906条经验 获得超10个赞
看 move({x: 3}),这里的 {x: 3} 对象的 y 为 undefined,
所以结果是 [3, undefined]
注意第二种 move 和 第一个 move 的区别,
第一个 move 中:
function move({x = 0, y = 0} = {}) {
return [x, y];
}
// 等价于
function move(a) {
if (a === undefined) {
a = {}
}
let x = a.x
if (x === undefined) {
x = 0
}
let y = a.y
if (y === undefined) {
y = 0
}
return [x, y]
}
而第二个 move 相当于:
function move(a = {x: 0, y: 0}) {
return [a.x, a.y];
}
// 等价于
function move(a) {
if (a === undefined) {
a = {x: 0, y: 0}
}
// 此处没有为 a.x 和 a.y 设置默认值的过程
return [a.x, a.y];
}
也就是当 a 为 undefined 时,a 取默认值 {x: 0, y: 0}.

TA贡献1875条经验 获得超5个赞
你可以从结构时的等号来看:
function move({x, y} = { x: 0, y: 0}) {...}
这里等号左边的部分会被看作一个整体来赋默认值,在题中第二个 move 里就是他的唯一一个输入值。
如果有输入,则对这个输入值进行结构,如果没有输入,则使用默认值。
可以注意到的是前面的 move 里有三个等号,后面 move 只有一个等号
添加回答
举报