为什么这个对象属性未定义? [英] Why is this object property undefined?
问题描述
请考虑以下代码。第一个 console.log
正确记录图像,您可以在下图中看到它的属性。但是,当我尝试将其属性记录到控制台时,我得到 undefined
!
Consider the code below. The first console.log
correctly logs the image, and you can see its properties in the image below. However, when I try logging one if its properties to the console, I get undefined
!
console.log(that.data[0].cards); //works -- see image below
console.log(that.data[0].cards.E); //undefined
console.log(that.data[0].cards['E']); //undefined
console.log(that.data[0].cards.hasOwnProperty('E')); //false
var test = JSON.stringify(that.data[0]);
console.log(test); // {}
for( var key in that.data[0].cards ) {
console.log('hello????') //doesn't appear in the console
}
console.log( Object.keys( that.data[0].cards ) ); //[]
console.log( that.data[0].cards.propertyIsEnumerable("E") ); //false
console.log( that.data[0].cards.__lookupGetter__( "E" ) ); //undefined
控制台中的结果:
任何想法这里发生了什么? that.data [0]
中的 xml
属性也应该包含其中的属性 - 命名相同,事实上,作为卡中的属性
。
Any idea what's going on here? The xml
property inside of that.data[0]
should also have properties inside of it -- named the same, in fact, as the properties in cards
.
FWIW,我在Firebug中得到了同样的东西(上面的控制台)图片是Chrome)。
FWIW, I get the same thing in Firebug (the above console image is Chrome).
推荐答案
我已经解决了这个问题。基本上,有问题的对象( that.data [0] .cards
)的属性由函数 a()$ c $创建c>在处理完必要XML文件的所有AJAX请求之后运行。我允许请求以异步方式运行,如果
a()
应该使用计数器在 success
回调函数中确定已经调用。
I've solved the problem. Basically, the object in question (that.data[0].cards
) has its properties created by a function a()
that runs after all the AJAX requests for the necessary XML files have been processed. I allow the requests to run asynchronously, using a counter to determine in the success
callback function if a()
should be called yet.
在 a()
运行后,函数 b()
应该在 that.data [i] .cards
上执行操作。但是, b()
在 a()
之前运行,因为 a( )
依赖异步请求。因此,解决方案只是使 a()
调用 b()
。
After a()
runs, function b()
is supposed to perform operations on that.data[i].cards
. However, b()
was running prior to a()
being called because of a()
's reliance on the asynchronous requests. So the solution was simply to make a()
call b()
.
所以这对我来说是一个非常简单的错误。让它如此混乱的原因是将卡
对象已经构建,实际上还没有。因此,控制台向我提供了不正确 - 或至少不清楚 - 的信息。
So this turned out to be a pretty simple mistake on my part. What made it so confusing was the fact that logging that.data[0].cards
to the console showed me that in fact the cards
object had already been built, when in fact it had not yet. So the console was providing me with incorrect--or at least unclear--information.
感谢大家昨晚的帮助!赞成四处:)
Thanks for everyone's help last night! Upvotes all around :)
这篇关于为什么这个对象属性未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!