简体   繁体   中英

JavaScript Two-Dimensional array is undefined

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.

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"]
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM