1

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.

2
  • locate['London'] is clearly undefined. Commented Aug 27, 2014 at 8:28
  • A 2x2 matrix / array in javascript is an Array inside an Array. Can you provide in matrix form what you are trying to put into the arrays? Are you try {[London, England], [John, Mike]}? Commented Aug 27, 2014 at 8:31

1 Answer 1

2

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

4 Comments

Also it should be locate = {}. This isn't an array ;)
@Derek朕會功夫: I missed the obvious, edited the answer :P
I like more your other way of declaration but it says its missing semicolon. Is this correct structure var locate = { London:{ England:["Jhon","Mike"] } }
I'm glad to be of help, @devjs11 :-). locate = {London:{England:"Jhon","Mike"]}} should work just fine.

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.