简体   繁体   English

JavaScript二维数组未定义

[英]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/ 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: 在将值分配给locate['London']['England'] ,您必须确保locate['London']是一个对象:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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