Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a 2d array of objects in javascript

Tags:

javascript

I have a javascript object -

cell{xPos, yPos};

I would like to create 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?

like image 272
elssar Avatar asked Feb 24 '23 18:02

elssar


2 Answers

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/

like image 196
Robert Avatar answered Feb 26 '23 09:02

Robert


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] = [];
}
like image 43
Naftali Avatar answered Feb 26 '23 09:02

Naftali