destructure并返回多个值



我是javascript的新手,现在正在学习析构函数。我试图实现的(在控制台中显示(是:

"姓名:Mike Smith,父亲:Harry Smith;

"姓名:Tom Jones,父亲:Richard Jones;

我收到错误消息,n没有定义,但应该可以吗?这是我一直在做的代码:

const people = [
{
name: 'Mike Smith',
family: {
mother: 'Jane Smith',
father: 'Harry Smith',
sister: 'Samantha Smith'
},
age: 35
},
{
name: 'Tom Jones',
family: {
mother: 'Norah Jones',
father: 'Richard Jones',
brother: 'Howard Jones'
},
age: 25
}
];
const kalle= people.map(( {name: n, family: {father: f}})=> { 
return [n,f]
});

console.log('Name: ' + n + ', Father: ' + f);
// "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"

nf在函数之外,这意味着您不能访问它们,而是在数组上循环。

除非值也是对象,否则破坏对象不需要键。

const people = [
{
name: 'Mike Smith',
family: {
mother: 'Jane Smith',
father: 'Harry Smith',
sister: 'Samantha Smith'
},
age: 35
},
{
name: 'Tom Jones',
family: {
mother: 'Norah Jones',
father: 'Richard Jones',
brother: 'Howard Jones'
},
age: 25
}
];
// Returns an array
const persons = people.map(({name, family: {father}})=> { 
return [name, father];
});
// Log each person
persons.forEach(([name, father]) => {
console.log(`Name: ${name}, Father: ${father}`);
});
// "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"

一个简单的join可能与您期望的相匹配

const people = [
{
name: "Mike Smith",
family: {
mother: "Jane Smith",
father: "Harry Smith",
sister: "Samantha Smith",
},
age: 35,
},
{
name: "Tom Jones",
family: {
mother: "Norah Jones",
father: "Richard Jones",
brother: "Howard Jones",
},
age: 25,
},
]
const kalle = people
.map(({ name: n, family: { father: f } }) => {
return "Name: " + n + ", Father: " + f
})
.join("n")
console.log(kalle)

相关内容

  • 没有找到相关文章

最新更新