开发者

Javascript Associative Arrays

开发者 https://www.devze.com 2022-12-27 17:14 出处:网络
It seems to me that this should work but I cant see what exactly is the pro开发者_运维技巧blem.

It seems to me that this should work but I cant see what exactly is the pro开发者_运维技巧blem.

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?


Your DDROA variable is only assigned after the object is created.
Therefore, when the object is initialized, DDROA is undefined.

To work around it, you should set RouteContext separately, like this:

var DDROA = {
    AllowedRoutes : {
        AR0 : {text : 'SomeText', value : 'SomeValue'},
        AR1 : {text : 'SomeText2', value : 'SomeValue2'}
    }
};
DDROA.RouteContext = {
    RC0 : {text : 'None', value : '0',
        AllowedRoutes : [ DDROA.AllowedRoutes.AR0 ]  //An error does not occur here
    }        
};

Also, when given a single argument, the Array 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消