Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
809 views
in Technique[技术] by (71.8m points)

javascript - typeof foo['bar'] !== 'undefined' vs. 'bar' in foo

What's the difference between the return values of these two expressions...

Expression 1: typeof foo['bar'] !== 'undefined'

Expression 2: 'bar' in foo

... assuming that these conditions are met:

  1. foo is an object,
  2. foo does not contain any properties that have the value undefined set explicitly.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The first tests the value of bar in foo.

The second tests for the existence of the bar property in foo.

var foo = {bar:undefined};

typeof foo['bar'] !== 'undefined'; // false

'bar' in foo;  // true

EDIT:

To add some clarification from the comments below, the issue OP is having is that accessing the domConfig property of window.document throws an Error.

This is an issue not related to the typeof operator, but rather to a specific issue with Firefox.

The issue has been documented here as a bug (back in 2003).

A few notable comments from that report:

Zbigniew Braniecki [:gandalf] 2003-11-19 09:09:31 PST

then why it can be iterated with for-in ?

Boris Zbarsky (:bz) 2003-11-19 09:24:05 PST

Because it is defined as a property on the nsIDOM3Document interface. It's just one that throws if you try to access its getter. ...

Zbigniew Braniecki [:gandalf] 2003-11-19 09:33:53 PST

... So what kind of bug is it?

The goal is to remove not implemented method/property from interface or to implement it?!?

Boris Zbarsky (:bz) 2003-11-19 09:53:23 PST

The goal is to eventually implement this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...