我正在与Javascript数据结构作斗争。我需要创建一个映射,其中键是一个字符串,值是两个long的数组。
例如:
var x = myMap["SomeString"];
var firstLong = x[0][0];
var secondLong = x[0][1];
// do something with first and second long
firstLong = x[1][0];
secondLong = x[1][1];
// do something with first and second long
etc..
如何在Javascript中正确实现此目的?
答案 0 :(得分:1)
javascript中的字典等效数据结构是基本的JavaScript对象。你可以尝试
var myMap = {
SomeString : [
[1,2],
[32222,44444]
]
}
并打印出来
答案 1 :(得分:1)
因此,为了使用多维数组,首先需要“定义”维度,即
var myMap = {};
myMap["SomeString"] = [];
myMap["SomeString"][0] = []; // new dimension
myMap["SomeString"][0][0] = 1; // can be also done with
myMap["SomeString"][0][1] = 2; // myMap["SomeString"][0].push(2);
myMap["SomeString"][1] = []; // new dimension
myMap["SomeString"][1][0] = 3;
myMap["SomeString"][1][1] = 4;
同样可以用文字来完成:
var myMap = {
SomeString: [
[1, 2],
[3, 4]
]
};
console.log(myMap["SomeString"][0][1]); // 2
答案 2 :(得分:0)
假设你实际上并不是指二维数组;
var myMap = {};
myMap["SomeString"] = [123, 456];
alert( myMap["SomeString"][0] );
alert( myMap["SomeString"][1] );