看这段代码:
let lecture = { id: 2, title: "MyTitle", topics: [ { title: "John", age: 1 }, { title: "John2", age: 2 }, { title: "John3", age: 3 } ] }我想提取数组中的主要title属性和第三个age(通过对象解构)
I want to extract the main title property and the third age in the array (via object destructuring)
我可以通过 :
let { title:lectureTitle , topics:[,,{age:thirdAge}]} = lecture; console.log(lectureTitle,thirdAge);//MyTitle 3问题
但是如果数组有 100 个项目并且我想要第 99 个 age 怎么办?
But what if the array has 100 items and I want the 99'th age ?
那我该怎么做呢?对象解构是否为此提供了解决方案?
How would then I do it ? Does object destructuring offer a solution for that?
推荐答案但是如果数组有 100 个项目并且我想要第 99 个年龄怎么办?
But what if the array has 100 items and I want the 99'th age ?
数组是对象,所以这样做:
Arrays are objects, so this will do:
let {title: lectureTitle, topics: {98: {age: thirdAge}}} = lecture;注意 然而,[...] 类型的解构适用于任何可迭代对象,而 {...} 仅适用于对象(以及数组).要使上述解决方案适用于任意可迭代对象,您必须展开可迭代对象并将其用数组包装.
Note however that the [...] type of destructuring works with any iterable, whereas {...} only works with objects (and therefore arrays). For the above solution to work with arbitrary iterables you will have to spread the iterable and wrap it with an array.
let {title: lectureTitle, topics: {98: {age: thirdAge}}} = [...lecture];更多推荐
长数组的对象解构解决方案?
发布评论