javascript / jquery - adding properties to an instantiated object
I am instantiating an object which builds an associative array. After it is instantiated, I want to add properties the object's members, but I'm gett开发者_开发百科ing an error when I attempt to do so.
So this is the object, which parses a bunch of xml and builds out the scenes and vehicles arrays:
var supertree = {
    scenes: {},
    vehicles: {},
    init: function() {
        this.parseScenes();
        this.parseVehicles();
    },
...
And when I instantiate the object:
supertree.init();
    supertree.ready = function() {
        assignSpritePos();
    }
I can't add properties to it. This is what I'm trying to do:
function assignSpritePos(){
    var sceneCount = 0;
    var sceneLength = Object.keys(supertree.scenes).length;
    for (i=0; i< sceneLength; i++){
        //console.log(i);
        supertree.scenes[i].index = i;
        sceneCount++;
    }
}
As you can see, all I'm really trying to do is store some permanent reference to its index in the overall object. How do I do this? The error I get is:
TypeError: 'undefined' is not an object (evaluating 'supertree.scenes[i].index = i')
Assigning properties to objects isn't recursive, i.e. it doesn't create objects automagically for you so you must assign each property individually.
Try this...
supertree.scenes[i] = { 'index': i };
You can't assign a property to an object that doesn't exist yet. Use this:
supertree.scenes[i] = {};
supertree.scenes[i].index = i;
 加载中,请稍侯......
      
精彩评论