对解构函数参数感到困惑
Confused about de-structuring function parameters
在下面的示例中,为什么 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 相反。
引擎盖下发生了什么?
displayName
和 firstName
分别是 assigned new names - displayName2
和 firstName1
,要访问这些值,您需要使用别名。
由于只有别名被定义为变量,因此尝试使用旧名称访问值将引发 "variable is not defined" 错误。
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
在解构赋值中,value位置成为赋值的变量。
在声明位置使用时(如函数参数),值位置的名称在赋值之前在当前范围内声明。
如您的示例所示,值位置也可以描述要解构的嵌套对象,然后期望值与所描述的结构匹配,其遵循上述相同的模式。
// The data object
const data = {foo: "bar"};
// A destructuring declaration and assignment.
// The assignment target's structure matches that of the data
let {foo: localVar} = data;
console.log(localVar); // bar
// Same, but using the existing `localVar` variable with no new declaration.
({foo: localVar} = {foo: "baz"});
console.log(localVar); // baz
在下面的示例中,为什么 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 相反。
引擎盖下发生了什么?
displayName
和 firstName
分别是 assigned new names - displayName2
和 firstName1
,要访问这些值,您需要使用别名。
由于只有别名被定义为变量,因此尝试使用旧名称访问值将引发 "variable is not defined" 错误。
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
在解构赋值中,value位置成为赋值的变量。
在声明位置使用时(如函数参数),值位置的名称在赋值之前在当前范围内声明。
如您的示例所示,值位置也可以描述要解构的嵌套对象,然后期望值与所描述的结构匹配,其遵循上述相同的模式。
// The data object
const data = {foo: "bar"};
// A destructuring declaration and assignment.
// The assignment target's structure matches that of the data
let {foo: localVar} = data;
console.log(localVar); // bar
// Same, but using the existing `localVar` variable with no new declaration.
({foo: localVar} = {foo: "baz"});
console.log(localVar); // baz