I have a javascript object -
cell{xPos, yPos};
I would like to creat开发者_开发技巧e a 2d array of this object.
cellPrototype = function(x, y) {
this.xPos = x;
this.yPos = y;
}
var cell = new Array();
for(var i=0;i<10;i++)
{
cell[i] = new Array();
for(var j=0;j<10;j++)
{
cell[i][j] = new cellPrototype(i,j);
}
}
This code doesn't work. Neither does -
var cellPrototype = function(x, y) {
return {
xPos : x;
yPos : y;
}
var cell = new Array();
for(var i=0;i<10;i++)
{
cell[i] = new Array();
for(var j=0;j<10;j++)
{
cell[i][j] = new cellPrototype(i,j);
}
}
So how do I create a 2d array of an object in javascript?
This works fine for me, I'm not sure if that's exactly the output you're looking for, where
Array[x][y]
will reference an object with points at x, y
.
var Coords = function(x, y) {
return {
"x" : x,
"y" : y
};
};
var Main = [];
for (var i = 0, l = 10; i < l; i++) {
Main[i] = [];
for (var j = 0, l2 = 10; j < l2; j++) {
Main[i][j] = Coords(i, j);
}
}
http://jsfiddle.net/robert/d9Tgb/
You can make a 2d array like so:
var new_array = [];
var arr_length = 10;
for(var i = 0; i < arr_length; ++i){
new_array[i] = [];
}
This post is a bit old, but here is another way to create a 2D array
var arr1=[];
var x=['a','b','c','d'];
var y=[1,2,3,4];
for( var i in x){
arr1.push([x[i],y[i]]); //For x and y of the same length
}
In JavaScript x and y can be objects arrays
jsFiddle It :)
make an empty array and push the child arrays onto it
var array = [];
array.push([1,2,3,4]);
//array[0][0] == 1
or all in one shot
var array = [[1,2,3,4], [1,2,3,4], [1,2,3,4]];
精彩评论