1

I've created a 2D array and interfaced with it quite a lot through my code, but when I try to do something like this:

worldmap[x][y].eventAct = function() { 
     State.updateState("WorldMap"); 
     console.log("Event called"); 
}

It doesn't work, however when I do this:

worldmap[x].eventAct = function() { 
     State.updateState("WorldMap"); 
     console.log("Event called"); 
}

It works, but it becomes useless as I don't know what x and y co-ords the event takes place, I only know the x!

Any help would be appreciated!

Rob
  • 13
  • 4
  • what exactly...is the issue? – markasoftware Nov 10 '13 at 03:47
  • When I do what I want, the first one, worldmap[x][y].eventAct = function() etc, and then I try to call it, even through the console it doesn't exist, whereas when I do the 2nd method with a standard array it works fine and the eventAct method is callable, if that makes any sense! – Rob Nov 10 '13 at 03:49
  • What is the value of `worldmap[x][y]`? Primitive values, such as from number or string literals, [can't really hold their own properties](http://stackoverflow.com/q/2739515). – Jonathan Lonowski Nov 10 '13 at 03:52
  • The value of worldmap[x][y] in this case: x = 14, y = 23 and the actual value of what's stored there is a string – Rob Nov 10 '13 at 03:55

1 Answers1

1

If the values in worldmap are all primitive values, then they simply can't hold properties.

var foo = 'bar';
foo.baz = 'qux';
console.log(foo.baz); // undefined

The property can be set because primitives can be boxed and treated as objects. But, the boxing doesn't persist, so the property is lost immediately after.

So, you could create the Object to hold the values and methods:

worldmap[x][y] = {
    value: worldmap[x][y],

    eventAct: function() {
        State.updateState("WorldMap");
        console.log("Event called");
    }
};
console.log(worldmap[x][y].value);

Or, similar to your 2nd snippet, you could attach the method to the arrays and accept the missing indices as arguments:

worldmap[x].eventAct = function (y) {
    var value = this[y];

    State.updateState("WorldMap"); 
    console.log("Event called");
};
Community
  • 1
  • 1
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199