定义javascript多维数组的问题

时间:2011-04-11 01:38:44

标签: javascript multidimensional-array

这是我的javascript代码,用于定义多维数组

    var array = new Array(2);
    for (i = 0; i < array.length; i++) {
        array[0] = new Array(4);
    }
    array[0][0] = "name1";
    array[0][1] = "property1";
    array[0][2] = "value1";
    array[0][3] = "0";

    //this is where the error happened
    array[1][0] = "name2";
    array[1][1] = "property2";
    array[1][2] = "value2";
    array[1][3] = "1";

但是萤火虫告诉我一个错误: 数组[1]未定义

我在上面的代码中标记

array [0] [] 我可以定义,并给它们值,

那么为什么问题发生在这个地方?谢谢

4 个答案:

答案 0 :(得分:2)

你的循环正在重新定义数组的第一个成员。

var array = new Array(2);
for (i = 0; i < array.length; i++) {
    array[i] = new Array(4);
}
array[0][0] = "name1";
array[0][1] = "property1";
array[0][2] = "value1";
array[0][3] = "0";

//this is where the error happened
array[1][0] = "name2";
array[1][1] = "property2";
array[1][2] = "value2";
array[1][3] = "1";

如果你正在做的就是你可以使用简写语法

var array = [
        [
            "name1",
            "property1",
            "value1",
            "0"
        ],
        [
            "name2",
            "property2",
            "value2",
            "1"
        ]
    ];

答案 1 :(得分:2)

array[0] = new Array(4)应为array[i] = new Array(4)

这可以通过数组文字更加简洁地完成:

var array = [
    ["name1", "property1", "value1", "0"],
    ["name2", "property2", "value2", "1"]
];

答案 2 :(得分:0)

JavaScript没有多维数组。但是,您可以拥有数组数组。以下是您可以创建所需内容的方法:

var array = [
    ["name1", "property1", "value1", "0"],
    ["name2", "property2", "value2", "1"]];

答案 3 :(得分:0)

注意:

for (i = 0; i < array.length; i++) {
    array[0] = new Array(4);
}

您始终在初始化array[0],但我认为您的意思是array[i]