hh54188
hh54188

Reputation: 15646

The problem in define javascript multidimensional array

this is my javascript code which for defining multidimensional array

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

but the firebug tell me an error: array[1] is not defined

which I mark in the code above

But the array[0][] I could defined,and give them value,

So why the problem happened in this place?Thank you

Upvotes: 0

Views: 1727

Answers (4)

Wayne
Wayne

Reputation: 60414

Notice:

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

You're always initializing array[0] but I think you mean to say array[i]

Upvotes: 0

Jacob
Jacob

Reputation: 78880

JavaScript doesn't have multidimensional arrays. However, you can have arrays of arrays. Here's how you can create what you're looking for:

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

Upvotes: 0

deceze
deceze

Reputation: 522382

array[0] = new Array(4) should be array[i] = new Array(4).

This can be done much more succinctly with array literals though:

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

Upvotes: 2

Jonathan
Jonathan

Reputation: 5993

Your loop is redefining the first member of the array.

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

If this is all you are doing you can to it using shorthand syntax

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

Upvotes: 2

Related Questions