[英]for…of iteration and destructuring with an object inside an array
根據Mozilla文檔 ,這里是如何在for of
循環中使用解構:
var 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
}
];
for (var {name: n, family: {father: f}} of people) {
console.log('Name: ' + n + ', Father: ' + f);
}
// "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"
我的問題是,如果family
對象位於數組中,正確的解構語法是什么,如下所示:
var people = [
{
name: 'Tom Jones',
family: [
{
mother: 'Norah Jones',
father: 'Richard Jones',
brother: 'Howard Jones'
}
],
age: 25
}
];
(注意額外的[方括號])
嘗試使用以下方法進行結構化:
for (var {name: n, family[0]: {father: f}} of people) {
console.log('Name: ' + n + ', Father: ' + f);
}
在方括號處出現Unexpected token
錯誤。
所以在這個例子中,我如何使用解構來為f
賦值?
您希望表示數組結構,而不是數組索引訪問。
var people = [{ name: 'Tom Jones', family: [{ mother: 'Norah Jones', father: 'Richard Jones', brother: 'Howard Jones' }], age: 25 }]; // Describe the structure -v-----------v for (var {name: n, family: [{father: f}]} of people) { console.log('Name: ' + n + ', Father: ' + f); }
當然,這假設您只想要第一個成員。 如果您需要更多,可以使用其余語法。
var people = [{ name: 'Tom Jones', family: [{ mother: 'Norah Jones', father: 'Richard Jones', brother: 'Howard Jones' }], age: 25 }]; for (var {name: n, family: [{father: f}, ...rem]} of people) { console.log('Name: ' + n + ', Father: ' + f); console.log("Remaining values: %s", rem.length); }
您可以使用數組解構(簡單地忽略任何剩余的數組元素):
// vv vv
for (var {name: n, family: [ {father: f} ] } of people)
// ...
或者,由於數組只是對象,因此您可以使用索引作為鍵的對象解構:
// vvvvv vv
for (var {name: n, family: { 0: {father: f} } } of people)
// ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.