簡體   English   中英

Javascript在數組上未定義

[英]Javascript gets undefined on array

我具有以下針對javascript的數據結構:

var data =  {
    "announcements": {
        "IFT4S": [{
            "id": "D7214",
            "read_state": "unread",
            "posted_at": "2018-10-25T14:35:54Z",
            "title": "Reminder! Systems disruption: 27-28 Oct",
            "message": "All University online systems will be unavailable."
        }, {
            "id": "B399C",
            "read_state": "read",
            "posted_at": "2018-10-22T09:04:48Z",
            "title": "Stem Fair",
            "message": "The STEM Careers Fair is taking place on 31 October 2018"
        }, {
            "id": "6F5EE",
            "read_state": "unread",
            "posted_at": "2018-10-22T09:04:48Z",
            "title": "Smile more, worry less with our FREE course",
            "message": "Take part in our Online Mindfulness Programme."
        }]
    }
}

我想訪問鍵“ read_state”,“ posted_at”,“ title”和“ message”的值。 但是,當我嘗試data.announcements.IFT4S["title"]或任何其他鍵而不是“ title”時,在控制台中得到的是未定義的。 我究竟做錯了什么?

您必須遍歷數組以從對象數組中獲取價值

 var data = { "announcements": { "IFT4S": [ { "id": "D7214", "read_state": "unread", "posted_at": "2018-10-25T14:35:54Z", "title": "Reminder! Systems disruption: 27-28 Oct", "message": "All University online systems will be unavailable." }, { "id": "B399C", "read_state": "read", "posted_at": "2018-10-22T09:04:48Z", "title": "Stem Fair", "message": "The STEM Careers Fair is taking place on 31 October 2018" }, { "id": "6F5EE", "read_state": "unread", "posted_at": "2018-10-22T09:04:48Z", "title": "Smile more, worry less with our FREE course", "message": "Take part in our Online Mindfulness Programme." }, ] } } data.announcements.IFT4S.forEach(item => { console.log(item.title) }) 

或者你可以這樣,索引是0

  console.log(data.announcements.IFT4S[0].read_state) console.log(data.announcements.IFT4S[0].title) 

當我嘗試data.announcements.IFT4S [“ title”]或任何其他鍵而不是“ title”時,在控制台中得到的是未定義的。 我究竟做錯了什么?

您在這里正在嘗試訪問IFT4S陣列的標題鍵。

問題是IFT4S沒有標題密鑰。 而是像數組對象一樣,將索引作為鍵。

IFT4S = [ {...}, {...}, {...} ]

要訪問IFT4S數組的第一個元素,您需要這樣做

IFT4S[0]

在您的情況下,該對象將返回IFT4S數組( 索引0 )的第一個位置

{
    id: "D7214",
    read_state: "unread",
    posted_at: "2018-10-25T14:35:54Z",
    title: "Reminder! Systems disruption: 27-28 Oct",
    message: "All University online systems will be unavailable."
}

如果要從IFT4S數組中的所有元素中獲取所有標題,則可以執行此操作

IFT4S.map(element => element.title)

Array.prototype.map返回一個新數組,其中每個元素都是將map內部指定的函數應用於原始數組的每個元素的結果。

在這種情況下,它將返回

[
    "Reminder! Systems disruption: 27-28 Oct",
    "Stem Fair",
    "Smile more, worry less with our FREE course"
]

IFT4S是一個數組,您可以通過調用以下內容來訪問其對象及其值:

data.announcements.IFT4S[index].title

由於數組包含3個對象,因此索引在此處為0-2之一。 例如:

data.announcements.IFT4S[0].title

這是一個非常基本的概念,請查看任何javascript指南以了解數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM