简体   繁体   English

具有多维数组的Javascript对象

[英]Javascript object with multidimensional array

I am very new to JavaScript. 我是JavaScript的新手。 I have following object in Java and I need to create equivalent in JavaScript but I am unable to achieve this: 我在Java中有以下对象,我需要在JavaScript中创建等效的但我无法实现这一点:

 Map<String, String[][]> objectName
var objectName = {
    'key1': [
      ['string1', 'string2'],
      ['string3', 'string4']
    ],
    'key2': [
      ['string5', 'string6']
    ]
}
console.log(objectName['key1'][0][0]) //string1

You can do it like this: 你可以这样做:

var objectName = {
    "first": [[1, 2], [2, 3]],
    "second": [[1, 2], [2, 3]]
};
 JSONObject json = new JSONObject(map);

JavaScript does not have a special syntax for creating multidimensional arrays. JavaScript没有用于创建多维数组的特殊语法。 A common workaround is to create an array of arrays in nested loops 常见的解决方法是在嵌套循环中创建数组数组

The following code example illustrates the array-of-arrays technique. 以下代码示例说明了数组数组技术。 First, this code creates an array f . 首先,此代码创建一个数组f Then, in the outer for loop, each element of f is itself initialized as new Array() ; 然后,在外部for循环中, f每个元素本身都被初始化为new Array() ; thus f becomes an array of arrays. 因此f成为一个数组的数组。 In the inner for loop, all elements f[i][j] in each newly created "inner" array are set to zero. 在内部for循环中,每个新创建的“内部”数组中的所有元素f[i][j]都被设置为零。

var iMax = 20;
var jMax = 10;
var f = new Array();

for (i=0;i<iMax;i++) {
 f[i]=new Array();
 for (j=0;j<jMax;j++) {
  f[i][j]=0;
 }
}

The Map part is easy: just create an object like this: Map部分很简单:只需创建一个这样的对象:

var mymap= {};

Then you can add entries like this: 然后你可以添加这样的条目:

mymap["A"]= ...

or 要么

mymap.A= ...

Now for the hard part, the 2D string array. 现在对于困难的部分,2D字符串数组。 Unfortunately (of fortunately, depending on your view) you can and need not define such an object. 不幸的是(幸运的是,取决于你的观点)你可以而且不需要定义这样的对象。 You would simply create it on the fly, like this: 您只需动态创建它,如下所示:

mymap["A"]= []; // this creates an empty array (first dimension)
mymap["A"][0]= []; // the array grows 1, containing a (2nd dim) empty array
mymap["A"][0].push("1");
mymap["A"][0].push("2"); // your first array contains one array of 2 strings
mymap["A"][1]= []; 
mymap["A"].push([]); // = mymap["A"][2]= []; 
// etc.

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

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