-
Hi,
I am having some problems with arrays, objects, and functions. I have a function that constructs an array of point objects. Here is a simple version of the function:
Code:
function makePoints(num);
pointList = new Array(num);
point = new Object();
for (j=1; j<=num; j++){
point.x = j;
point.y = j;
pointList[j] = point;
}
return pointList;
}
I am calling the function like this:
Code:
myPoints = makePoints(3);
I would expect the results to be:
myPoints[1].x:1
myPoints[1].y:1
myPoints[2].x:2
myPoints[2].y:2
myPoints[3].x:3
myPoints[3].y:3
But instead I get:
myPoints[1].x:3
myPoints[1].y:3
myPoints[2].x:3
myPoints[2].y:3
myPoints[3].x:3
myPoints[3].y:3
Where am I going wrong? Is it possible to pass an array back as the result of a function?
I can see other ways to do this. But I would really like to be able to do it in this way. Can anyone help?
Thanks
Bangers
-
You'er not creating a class of point objects, you're recreating a single point object every time through the loop.
Code:
function point (j) {
this.x = j;
this.y = j;
}
function makePoints (num) {
var j = new Number();
pointList = new Array(num);
for (j=1; j<=num; j++) {
pointList[j] = new point(j);
}
return pointList;
}
myPoints = new Array;
myPoints = makePoints(3);
var j = new Number();
for (j=1; j < myPoints.length; j++) {
trace ("myPoints["+j+"].x,myPoints["+j+"].x = " + myPoints[j].x + ", " + myPoints[j].y);
}
Code tested and working in Flash 5