繁体   English   中英

提取数组的元素

[英]Extracting elements of an array

我在访问单个元素时遇到了一些麻烦,例如数组中的“fullName”。

[
    {
        pk: "pk1",
        sk: "sk1",
        entity: "entity1",
        id: "id1",
        companyId: "companyId",
        country: "country",
        location: "location",
        title: "title1",
        description: "Description1",
        startDate: "2021-02-19T11:44:08.079Z",
        endDate: "2022-01-05T11:44:08.079Z",
        type: 10,
        participationType: 1,
        participants: [
            {
                mapOfPoints: [],
                fullName: "Full Name1",
                userId: "user-id-1",
                dateJoined: "2020-05-25T15:22:45.941Z",
                points: 10
            }
        ],
        prizes: [
            {
                conditionValue: "1st",
                conditionType: "RANKING",
                prizeValue: 100,
                prizeType: "COINS"
            }
        ],
        imageUrl: "ImageURL1"
    }
    ,
    {
        pk: "pk2",
        sk: "sk2",
        entity: "entity2",
        id: "id2",
        companyId: "companyID",
        title: "title2",
        description: "Description2",
        startDate: "2021-04-27T13:39:21.000Z",
        endDate: "2021-04-29T13:39:21.000Z",
        type: 0,
        participationType: 1,
        participants: [
            {
                mapOfPoints: [],
                fullName: "Full Name2",
                userId: "test-user-2",
                dateJoined: "2021-04-26T14:46:55.963Z",
                points: 0
            }
        ],
        prizes: [
            {
                conditionValue: "1st",
                conditionType: "RANKING",
                prizeValue: 100,
                prizeType: "COINS"
            }
        ],
        imageUrl: "ImageURL2"
    }
]

我尝试使用 for 循环访问数组的各种元素,但无济于事。 以下是 for 循环的示例:

     for (var i = 0; i < res.length; i++) {
       console.log("Element: ",res[i].participants[i])
   }

我得到的结果是第一个元素会成功打印出来,但循环会在第二次迭代时崩溃。

我希望能够访问数组中的元素,欢迎提供任何帮助。

您对res数组和participants数组使用相同的索引。 您需要有不同的索引:

for (var i = 0; i < res.length; i++) {
  for (var j = 0; j < res[i].participants.length; j++) {
    console.log("Element: ",res[i].participants[j])
   }
}

或者使用 Array 方法更好

res.forEach((el, i) => {
  console.log('Element: ', i)
  el.participants.forEach(participant => {
    console.log('Participant: ', participant)
  })
})

您的方法的问题是在resparticipants arrays 中使用i变量作为键。 你需要这样的东西:

for (var i = 0; i < myArray.length; i++) {

  for (var z = 0; z < myArray[i].participants.length; z++) {

       console.log("Element: ", myArray[i].participants[z])
   }

 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM