2017-09-23 89 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

是的,这个也适用。我会标记为答案,但其他人是第一,并且比你少点:)谢谢你的朋友 –