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!

4
  • what exactly...is the issue? Commented Nov 10, 2013 at 3: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! Commented Nov 10, 2013 at 3: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. Commented Nov 10, 2013 at 3: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 Commented Nov 10, 2013 at 3:55

1 Answer 1

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");
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.