简体   繁体   English

解构并返回多个值

[英]destructure and return multiple values

I'm new on javascript and learning now destructuring.我是 javascript 的新手,现在正在学习解构。 What i'm trying to achieve(get shown in console) is this:我想要实现的(在控制台中显示)是这样的:

"Name: Mike Smith, Father: Harry Smith" “姓名:迈克·史密斯,父亲:哈里·史密斯”

"Name: Tom Jones, Father: Richard Jones" “姓名:汤姆·琼斯,父亲:理查德·琼斯”

I'm getting error message that n is not defined but it should be ok?我收到错误消息n 未定义但应该没问题? here is my code what i have been doing:这是我一直在做的代码:

 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"

n and f are outside the function which means you can't acces them instead loop over the array. nf在 function 之外,这意味着您不能访问它们,而是在数组上循环。

Destructuring objects don't need a key unless the value is an object as well.解构对象不需要键,除非值也是 object。

 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"

A simple join may match what you expect一个简单的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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM