Reputation: 1948
I was trying to resolve my error with other answers but just fail. I have this simple example of what I think is two-dimensional array but it keeps returning me undefined error.
var city = 'London',
country = 'England';
var locate = [];
locate['London']['England'] = ['Jhon','Mike'];
for (i = 0; i < locate[city][country].length; i++) {
console.log(locate[city][country][i]);
}
jsbin http://jsbin.com/pixeluhojawa/1/
what am I doing wrong in this example, I would appreciate your help.
Upvotes: 1
Views: 814
Reputation: 72839
Before you can assign a value to locate['London']['England']
, you'll have to make sure that locate['London']
is an object:
var locate = {};
locate['London'] = {};
locate['London']['England'] = ['Jhon','Mike'];
Notice how I used an object literal ({}
) instead of an array literal ([]
). Arrays don't support string keys like this. You'll need to use objects instead.
You can also declare it like this::
var locate = {
London:{
England:["Jhon","Mike"]
}
}
Upvotes: 2