简体   繁体   中英

js object returns undefined even though property is there

I check for a property on an object but it returns undefined even though it is there. I assume I am testing in the wrong way?

I run this

console.log(self.modules[moduleId]);

and it outputs this:

Object

    composed: Array[2]

    prototypes: Array[2]

    slideshow: Slideshow

        cardFront: false

        currentSlide: 2

(So "slideshow" is an object, an instance of my class "Slideshow".)

I step in one step further to do this:

console.log(self.modules[moduleId].slideshow);

And it returns undefined.

My if-statement looks like this, although above is probably enough to get my issue.

if ( typeof( self.modules[moduleId].slideshow == 'undefined' ) ) {

The parantheses in your if-clause are wrong. With the parentheses you have, typeof operates on the value of the comparison expression, which is always a boolean .

Instead, use either

if (typeof self.modules[moduleId].slideshow == 'undefined')

...which will be true if slideshow doesn't exist at all on the object, or if it exists but has the value undefined .

Or make use of the in operator

if ('slideshow' in self.modules[moduleId])

...which will be true if the object or its prototype has the property, regardless of its value.

Or use hasOwnProperty :

if (self.modules[moduleId].hasOwnProperty('slideshow'))

...which will be true if the object itself (not its prototype) has the property, regardless of its value.

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