我正在与Javascript数据结构作斗争。我需要创建一个映射,其中键是字符串,值是两个长数组。
例如:
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中正确实现这一点?
因此,为了使用多维数组,首先需要"定义"维度,即
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;
同样可以使用literal:
var myMap = {
SomeString: [
[1, 2],
[3, 4]
]
};
console.log(myMap["SomeString"][0][1]); // 2
javascript中的字典等效数据结构是javascript的基本对象。你可以试试
var myMap = {
SomeString : [
[1,2],
[32222,44444]
]
}
假设你指的不是2d数组;
var myMap = {};
myMap["SomeString"] = [123, 456];
alert( myMap["SomeString"][0] );
alert( myMap["SomeString"][1] );