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] = "v开发者_运维知识库alue2";
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
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"]
];
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"
]
];
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"]];
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]
精彩评论