Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
84
rated 0 times [  89] [ 5]  / answers: 1 / hits: 25030  / 13 Years ago, tue, june 28, 2011, 12:00:00

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?


More From » javascript

 Answers
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/


[#91452] Monday, June 27, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mitchellg

Total Points: 235
Total Questions: 117
Total Answers: 106

Location: Fiji
Member since Wed, Jul 14, 2021
3 Years ago
mitchellg questions
Sun, Jan 10, 21, 00:00, 3 Years ago
Fri, Aug 21, 20, 00:00, 4 Years ago
Fri, Jul 10, 20, 00:00, 4 Years ago
;