JavaScript 关联数组
在我看来这应该可行,但我看不出到底是什么问题。
我收到的错误是“DDROA 未定义”
任何人都可以帮助启发我。
var DDROA = {
AllowedRoutes : {
AR0 : {text : 'SomeText', value : 'SomeValue'},
AR1 : {text : 'SomeText2', value : 'SomeValue2'}
},
RouteContext : {
RC0 : {text : 'None', value : '0',
AllowedRoutes : new Array(
DDROA.AllowedRoutes.AR0 // An error occurs here
)
}
}
}
编辑
Slack 的评论 您能否帮助解释一下为什么我必须完成声明 DDROA.AllowedRoutes,然后再声明一条语句以在单独的语句中添加 DDROA.RouteContext。本质上,你是在告诉我,我必须
var DDROA = {AllowedRoutes : {}};
那么
DDROA.RouteContext = {};
为什么这两个单独的陈述。我做类似的事情
var Utilities = {
TextBased : {
someFunction : function(){
//do stuff
},
someFunction2 : function() {
Utilities.TextBased.someFunction();
}
}
};
有什么区别?在我看来我应该得到同样的错误?
It seems to me that this should work but I cant see what exactly is the problem.
The error Im receiving is "DDROA is not defined"
Could anyone help enlighten me.
var DDROA = {
AllowedRoutes : {
AR0 : {text : 'SomeText', value : 'SomeValue'},
AR1 : {text : 'SomeText2', value : 'SomeValue2'}
},
RouteContext : {
RC0 : {text : 'None', value : '0',
AllowedRoutes : new Array(
DDROA.AllowedRoutes.AR0 // An error occurs here
)
}
}
}
EDIT
For Slack's Comment
Can you help explain why I must finish declaring the DDROA.AllowedRoutes and then make another statement to add DDROA.RouteContext in a separate stament. Essentially you are telling me I must
var DDROA = {AllowedRoutes : {}};
then
DDROA.RouteContext = {};
Why the two separate statements. I do things like
var Utilities = {
TextBased : {
someFunction : function(){
//do stuff
},
someFunction2 : function() {
Utilities.TextBased.someFunction();
}
}
};
What is the difference? It seems to me I should get the same error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
DDROA
变量仅在创建对象之后才分配。因此,当对象初始化时,
DDROA
为undefined
。要解决此问题,您应该单独设置
RouteContext
,如下所示:此外,当给定单个参数时,Array
构造函数采用 length 的数组。要创建包含单个元素的数组,请使用数组文字,如下所示[ DDROA.AllowedRoutes.AR0 ]
。来回答您编辑的问题,函数内的代码仅在调用函数时执行,即在分配变量之后。
Your
DDROA
variable is only assigned after the object is created.Therefore, when the object is initialized,
DDROA
isundefined
.To work around it, you should set
RouteContext
separately, like this:Also, when given a single argument, theArray
constructor takes the length of the array.To make an array with a single element, use an array literal, like this[ DDROA.AllowedRoutes.AR0 ]
.To answer your edited question, the code inside the function is only executed when the function is called, which is after the variable is assigned.
您的第二个示例起作用的原因是因为您正在定义一个函数,因此在调用该函数之前不会执行其中的代码,此时您的对象已完全实例化并且对子对象的引用有效。在第一个示例中,当您尝试访问该对象时,该对象尚不存在。
The reason your second example works is because you're defining a function, and so the code within it isn't executed until you invoke the function, at which point your object is fully instantiated and the reference to the child object is valid. In your first example the object doesn't yet exist when you attempt to access it.