[英]Why am I getting “Can not read property 0 of undefined”, when the object is very much there and I am trying to access it within scope?
I have a function like 我有一个像
(function next(index) {
var someObject = { 0:{some:"one"}, 1:{thing:"none"}, 2:{seconds: 5} };
setTimeout(function() {
//code ...
}, (someObject[0][seconds]*1000) );
)(0);
And I am getting the following error in the second last line 我在倒数第二行中收到以下错误
myscript.js:7 Uncaught TypeError: Cannot read property '0' of undefined
It seems to be a scope problem, because I tried to access the 0th key like someObject[0] as well as someObject.0 but no luck. 这似乎是一个范围问题,因为我尝试访问第0个键,如someObject [0]和someObject.0,但是没有运气。
But according to my understanding, someObject
is defined in the same scope as the call to setTimeout()
. 但是据我了解,
someObject
是在与setTimeout()
调用相同的范围内定义的。 So why am I getting this error. 那我为什么会收到这个错误。 How co I fix this?
我该如何解决?
When you access [seconds]
using bracket notation, it attempts to evaluate the variable seconds
and uses that result to determine the property to access. 当您使用括号表示法访问
[seconds]
,它将尝试评估变量seconds
并使用该结果来确定要访问的属性。 Specify it in string format ['seconds']
or use period notation as noted here: 以字符串格式
['seconds']
或使用句点符号指定它,如下所示:
var someObject = { 0:{some:"one"}, 1:{thing:"none"}, 2:{seconds: 5} }; try { console.log(someObject[2][seconds]*1000); } catch (e) { console.log(e.message); } console.log(someObject[2].seconds*1000);
Additionally: someObject[0]
is {some: "one"}
which doesn't have any seconds
parameter on it. 另外:
someObject[0]
是{some: "one"}
,上面没有任何seconds
参数。 I suspect you were trying to demonstrate someObject[2]
instead. 我怀疑您是在尝试演示
someObject[2]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.