2017-09-23 88 views
1

按照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

回答

9

您希望表示數組結構,而不是數組索引訪問。

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); 
 
}

+0

這很好用!謝謝。現在不需要其餘的語法,但將它歸檔以備將來參考 –

+0

是的,不客氣。 – llama

2

可以使用陣列解構(任何剩餘的數組元素被簡單地忽略):

     // vv   vv 
for (var {name: n, family: [ {father: f} ] } of people) 
    // ... 

或者,由於陣列只是對象,可以使用對象與解構索引作爲關鍵字:

     // vvvvv   vv 
for (var {name: n, family: { 0: {father: f} } } of people) 
    // ... 
+0

是的,這個也適用。我會標記爲答案,但其他人是第一,並且比你少點:)謝謝你的朋友 –