简体   繁体   中英

Object shows up in console but always adds an undefined or empty array at start

I am trying to perform some logic on an object. When I print the object to the console console.log(question); I see the object as follows:

[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] }

However, I am having trouble actually referencing the values. When I try question['text'] I get a type error:

undefined is not an object (evaluating 'question["text"]')

I see that there is an undefined being logged on the Console but cannot understand where there comes from.

As a note, my object is pulled from an array of objects as:

question = this.state.questions[1];

Where the questions are being pulled from the state.

When I log this.state.questions to the console, I dont see anything undefined, and rather, I see an empty array added at top:

[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 leads me to believe that

From the information given, the property is accessed before the data is actually inside the state. Trying to access "this.state.questions[1]" will give undefined if the data has not been previously loaded in (even if "this.state.questions" is an empty array).

To avoid this, make sure any function that is utilizing this value is either: an async function chained onto whatever function is getting data, or use conditionals to ensure the value isn't undefined. For example:

if(typeof this.state.questions[1] !== "undefined") {
 //do something
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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