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
5 Answers
Reset to default 4var 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
版权声明:本文标题:java - Javascript object with multidimensional array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741480936a2381166.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论