长阵列的对象解构解决方案? [英] Object destructuring solution for long arrays?

查看:112
本文介绍了长阵列的对象解构解决方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看以下代码:

let lecture = {
    id: 2,
    title: "MyTitle",
    topics: [
    {
        title: "John",
        age: 1
    },
    {
        title: "John2",
        age: 2
    },
    {
        title: "John3",
        age: 3
    }]
}

我想提取主要的标题属性和数组中的第三个年龄(通过对象解构)

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

问题

Question

但是,如果数组有100个项目,而且我想要第99个年龄

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;






注意 [...] 解构类型可以使用任何可迭代的方式,而 {...} 仅适用于对象(因此阵列)。所以上面的解决方案不适用于任意迭代(并且这个AFAIK没有一般的解决方案)。


Note however that the [...] type of destructuring works with any iterable, whereas {...} only works with objects (and therefore arrays). So the solution above wouldn't work with arbitrary iterables (and there is no general solution for this AFAIK).

这篇关于长阵列的对象解构解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆