6

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?

3
  • 1
    Unless I've misunderstood your question, your first example seems to work fine: jsfiddle.net/tgz22 Commented Jun 28, 2011 at 17:51
  • What doesn't work? The second one at least give me an array with 10 arrays of 10 cellPrototypes each... Commented Jun 28, 2011 at 17:52
  • @James @josh.trow Don't know what happened. I have been testing this code on my computer for the last hour or two trying to make out what went wrong. After fiddling in jsFiddle for a bit I got it to work. Dunno, maybe some small typo somewhere was the problem. Everyone who answered & commented, thank you for your help. Commented Jun 28, 2011 at 18:32

4 Answers 4

7

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/

Sign up to request clarification or add additional context in comments.

Comments

2

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] = [];
}

Comments

0

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 :)

Comments

-1

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

1 Comment

Those are not objects.

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.