JP *_*Lew 2 javascript destructuring ecmascript-6
根据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"
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果family对象位于数组中,正确的解构语法是什么,如下所示:
var people = [
{
name: 'Tom Jones',
family: [
{
mother: 'Norah Jones',
father: 'Richard Jones',
brother: 'Howard Jones'
}
],
age: 25
}
];
Run Code Online (Sandbox Code Playgroud)
(注意额外的[方括号])
尝试使用以下方法进行结构化:
for (var {name: n, family[0]: {father: f}} of people) {
console.log('Name: ' + n + ', Father: ' + f);
}
Run Code Online (Sandbox Code Playgroud)
Unexpected token在方括号处给出错误.
所以在这个例子中,我如何使用解构来赋值f?
lla*_*ama 10
您希望表示数组结构,而不是数组索引访问.
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);
}Run Code Online (Sandbox Code Playgroud)
当然,这假设您只想要第一个成员.如果您需要更多,可以使用其余语法.
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);
}Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
95 次 |
| 最近记录: |