【问题标题】:js object returns undefined even though property is therejs 对象返回 undefined 即使属性存在
【发布时间】:2014-02-04 21:52:53
【问题描述】:

我检查对象上的属性,但它返回未定义,即使它存在。我假设我以错误的方式进行测试?

我运行这个

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

它会输出这个:

Object

    composed: Array[2]

    prototypes: Array[2]

    slideshow: Slideshow

        cardFront: false

        currentSlide: 2

(所以“slideshow”是一个对象,是我的类“Slideshow”的一个实例。)

我更进一步做到这一点:

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

它返回未定义。

我的 if 语句看起来像这样,尽管上面可能足以解决我的问题。

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

【问题讨论】:

  • 你能发布你的代码的 jsfiddle 吗?
  • 如果self.modules[moduleId] 确实是您引用的对象结构,那么显然self.modules[moduleId].slideshow 不是 undefined。所以在问题的形成过程中丢失了一些东西。
  • @digitalextremist 不正确 - 在您的情况下,不应引用 'undefined'。
  • 你的括号是错误的。 if(typeof self.modules[moduleId].slideshow == 'undefined') 是正确的(或 if((typeof self.modules[moduleId].slideshow) == 'undefined'),但这些都是不必要的)。而且,另一件事:请记住,这只检查.slideshow。如果modules[moduleId] 在第一个位置中不存在,您仍然会收到错误 - 所以请先检查那个。
  • @aduch:并不是() 造成“歧义”,而是他们使表达错误。 == 将始终返回一个布尔值。 typeof 将始终为"boolean"(),就像OP 的问题一样,因为() 使typeof 适用于表达式 而不是self.modules[moduleId]

标签: javascript class object undefined


【解决方案1】:

你的 if 子句中的括号是错误的。使用括号,typeof 对比较表达式的值进行操作,该值始终为 boolean

相反,使用任一

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

...如果slideshow 在对象上根本不存在,或者如果它存在但具有值undefined,则为真。

或者使用inoperator

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

...如果对象或其原​​型具有该属性,则无论其值如何,这都是真的。

或者使用hasOwnProperty:

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

...如果对象本身(而不是其原型)具有该属性,则无论其值如何,这都是正确的。

【讨论】:

  • 不错的补充,@T.J.Crowder,感谢!
猜你喜欢
  • 1970-01-01
  • 2020-02-25
  • 2013-05-07
  • 2014-03-15
  • 1970-01-01
  • 2020-05-17
  • 1970-01-01
  • 2017-09-17
  • 1970-01-01
相关资源
最近更新 更多