对解构函数参数感到困惑 [英] Confused about de-structuring function parameters
问题描述
在下面的示例中,whois()函数为什么可以访问displayName2和name1?
In the following example why does the whois() function have access to displayName2 and 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.
To the untrained eye it looks like it should have access to displayName and fullName.firstName. The destructuring looks like JSON in reverse.
引擎盖下发生了什么事?
What's happening under the hood?
推荐答案
displayName
and firstName
were assigned new names - displayName2
and firstName1
receptively, and to access the values, you need to use the alias.
由于仅将别名定义为变量,因此尝试使用旧名称访问值将引发未定义变量"错误.
Since only the aliases are defined as variables, trying to access the values using the old names, will throw a "variable is not defined" error.
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
此外,在与计算的属性名称,您必须将其分配给新的变量名称:
In addition, when using destructuring with computed property names, you must assign it to a new variable name:
const prop = 'a';
const destructure1 = ({ [prop]: aa }) => console.log(aa);
destructure1({ a: 5 }); // gets the value
这篇关于对解构函数参数感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!