javascript - 对解构函数参数感到困惑

标签 javascript ecmascript-6 destructuring

在下面的示例中,为什么 whois() 函数可以访问 displayName2 和 name1?

function whois({displayName: displayName2, fullName: {firstName: name1}}){
  console.log(`${displayName2} is ${name1}`)
}

let user = {
  displayName: "jdoe",
  fullName: {
      firstName: "John",
      lastName: "Doe"
  }
}
whois(user) // "jdoe is John"

对于未经训练的人来说,它看起来应该有权访问 displayName 和 fullName.firstName。解构看起来就像 JSON 的反转。

幕后发生了什么?

最佳答案

displayNamefirstNameassigned new names - displayName2firstName1 可以接受,并且要访问这些值,您需要使用别名。

由于只有别名被定义为变量,尝试使用旧名称访问值将引发“变量未定义”错误。

const destructure1 = ({ a: aa }) => console.log(aa);
destructure1({ a: 5 }); // gets the value

const destructure2 = ({ a: aa }) => console.log(a);
destructure2({ a: 5 }); // throw an error because a is not defined

此外,当使用 computed property names 进行解构时,您必须将其分配给新的变量名称:

const prop = 'a';

const destructure1 = ({ [prop]: aa }) => console.log(aa);
destructure1({ a: 5 }); // gets the value

关于javascript - 对解构函数参数感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46878587/

相关文章:

javascript - js 解构赋值在 while 循环中不起作用

python - 为什么解构增强赋值不可能?

javascript - 在 javascript 文件中使用动态 html

javascript - 变量值未附加到 h2 元素中

javascript - 在 Web 服务器上保护 PHP JSON 输出结果

javascript - '不支持 ES 模块的 require()。 ' Node.js、express、swagger-jsdoc 出错

javascript - HTML5 promise : does resolve call end promise

javascript - “箭头功能”和“功能”是否等效/可互换?

javascript - 如何解构存储为状态值的对象

javascript - 使用 webpack 提取 Scss