A Flash Developer Resource Site

Results 1 to 2 of 2

Thread: Return Array from function?

  1. #1
    Senior Member
    Join Date
    Aug 2000
    Posts
    105
    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



  2. #2
    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  




Click Here to Expand Forum to Full Width

HTML5 Development Center