[英]Object shows up in console but always adds an undefined or empty array at start
我正在嘗試對對象執行一些邏輯。 當我將對象打印到控制台時console.log(question);
我看到的對象如下:
[15:23:06] undefined
[15:23:06] Object {
[15:23:06] "id": "213a3e34-1a86-4ae5-bd7c-c882fd1684f8",
[15:23:06] "text": "What is 4+4",
[15:23:06] }
但是,我在實際引用值時遇到了麻煩。 當我嘗試question['text']
出現類型錯誤:
undefined不是對象(評估'question [“ text”]')
我看到控制台上記錄了一個未定義的消息,但無法理解它的來源。
注意,我的對象是從對象數組中提取的,如下所示:
question = this.state.questions[1];
問題是從哪里來的。
當我將this.state.questions
登錄到控制台時,沒有看到未定義的任何內容,而是在頂部添加了一個空數組:
[15:22:11] Array []
[15:22:11] Array [
[15:22:11] Object {
[15:22:11] "id": "407e7560-a0cd-4272-bafc-795f5e5787be",
[15:22:11] "text": "What is 2+4",
[15:22:11] },
[15:22:11] Object {
[15:22:11] "id": "213a3e34-1a86-4ae5-bd7c-c882fd1684f8",
[15:22:11] "text": "What is 4+4",
[15:22:11] },
[15:22:11] Object {
[15:22:11] "id": "9d38c759-6b64-4c1f-9e0e-d3b95a72b3a8",
[15:22:11] "text": "What is 1+2",
[15:22:11] },
[15:22:11] ]
這使我相信
根據給定的信息,可以在數據實際進入狀態之前訪問該屬性。 如果以前未加載數據,則嘗試訪問“ this.state.questions [1]”將給出未定義的消息(即使“ this.state.questions”為空數組)。
為避免這種情況,請確保使用此值的任何函數是:鏈接到正在獲取數據的任何函數上的異步函數,或使用條件確保該值未定義。 例如:
if(typeof this.state.questions[1] !== "undefined") {
//do something
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.