0

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

4 Answers 4

2

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"]
];
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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

5 Comments

JavaScript doesn't have multidimensional arrays. What did you just create ?
That's not a multidimensional array then?
Why the downvote? Arrays of arrays are not the same thing as multidimensional arrays. A multidimensional array is an array with two fixed dimensions; JavaScript only has one-dimensional arrays which can contain other arrays as members.
In very strict mathematical terms you are right, but the common usage of "multidimensional array" means "array of arrays". :)
Not true even in programming terms. What is being created is a jagged array.
0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.