简体   繁体   中英

Cannot read property 'variable' of undefined

I am navigating an object that contains an array of objects.

When I use chrome's js developer console I can grab the title property from the first item in the array ie

hello.example.array[0].title

this returns the title (only in the js developer console). However when I write a script to do this for me suddenly I receive this response:

Cannot read property 'array' of undefined

here is an example of my js

var theTitle = hello.example.array[0].title;
console.log(theTitle);

Why does the console find it correctly when my js does not?

Try selecting the expression in question in the script view and then use the Ctrl-Shift-E shortcut to evaluate in the console. Or, copy-and-paste from the script view into the console. Or, hover over the last component of the expression in the script view to see the value. In either case, you will most likely find that you've mistyped something, or are executing the script in a different context than that in which you are evaluating the expression in the console, etc.

Thanks to @Barmar, I realized I needed to view how I was going about grabbing the 'title' property.

My solution was in the context of other code and how the object was being created in the first place.

Thanks all for the help!


Edit 6 Years later: This post has some popularity so I thought I would update it with a more valid answer...

  1. Make sure your JavaScript actually has the scope/context of the object to begin with.

  2. The JS Console is able to return it because it is being executed after the code has run.. whereas the JavaScript in question might be trying to access the variable before it is set.

So check if you have the right scope/context and that the code is not trying to access a variable before it has been set.

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