Question

I'm struggling with this concept. Is is possible in javascript to create a user defined so I can use

polygon[i].x
polygon[i].y

instead of

polygon[i][0]
polygon[i][1]

The code for polygon[i][j] is below.

var polygon = new Array();
for (i = 0; i < 4; i++)
{
    polygon[i] = new Array(2);
    for (j = 0; j < 2; j++)
    {
        polygon[i][j] = "[" + i + "," + j + "]";
    }
}

for (var i = 0; i < polygon.length; i++)
{
    alert(polygon[i][1]);
}
Was it helpful?

Solution

As far as I could understand your code, this would be it:

var polygon = [],
    i;

//push an object with x and y into the polygon array
for (i = 0; i < 4; i++){
  polygon.push({
    x : 'x @'+i,
    y : 'y @'+i
  });
}

//accessible as
polygon[index].x
polygon[index].y
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top