按照Mozilla docs內的對象解構,這裏是如何使用解構一個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
?
這很好用!謝謝。現在不需要其餘的語法,但將它歸檔以備將來參考 –
是的,不客氣。 – llama