admin管理员组

文章数量:1289827

I am very new to JavaScript. I have following object in Java and I need to create equivalent in JavaScript but I am unable to achieve this:

 Map<String, String[][]> objectName

I am very new to JavaScript. I have following object in Java and I need to create equivalent in JavaScript but I am unable to achieve this:

 Map<String, String[][]> objectName
Share Improve this question asked Mar 8, 2017 at 7:45 LennyLenny 9171 gold badge14 silver badges37 bronze badges 1
  • Possible duplicate of stackoverflow./questions/38567371/… – Shakti Phartiyal Commented Mar 8, 2017 at 7:47
Add a ment  | 

5 Answers 5

Reset to default 4
var objectName = {
    'key1': [
      ['string1', 'string2'],
      ['string3', 'string4']
    ],
    'key2': [
      ['string5', 'string6']
    ]
}
console.log(objectName['key1'][0][0]) //string1

The Map part is easy: just create an object like this:

var mymap= {};

Then you can add entries like this:

mymap["A"]= ...

or

mymap.A= ...

Now for the hard part, the 2D string array. 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.

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. A mon 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. Then, in the outer for loop, each element of f is itself initialized as new Array(); thus f bees an array of arrays. In the inner for loop, all elements f[i][j] in each newly created "inner" array are set to zero.

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;
 }
}

本文标签: javaJavascript object with multidimensional arrayStack Overflow