为什么变量“y”的值为 5?不是7?

Alf*_*lfi 3 javascript object destructuring

首先抱歉我的英语不好

所以,这是我的代码:

let x = 5
const {x: y=7} = {x}

console.log(y) // output is 5
Run Code Online (Sandbox Code Playgroud)

但为什么是 5?不是7?

Bar*_*mar 8

{x}是 的简写{x: x}。由于价值x就是5,这相当于{x: 5}

这意味着您的代码等效于

const {x: y=7} = {x: 5}
Run Code Online (Sandbox Code Playgroud)

这将设置y为 中的x属性值{x: 5}。如果没有属性,它将使用默认值7; 但由于该属性确实存在,因此使用了它的值,因此它设置y5

与之比较

let a = 5;
const {x: y=7} = {a}
Run Code Online (Sandbox Code Playgroud)

这将设置y7因为x对象中没有属性。