Constructor and array argument

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Peter Cartwright

    #1

    Constructor and array argument

    I'm trying to create an array of row objects containing 'source'
    arrays, which in the actual script are node values. The problem is the
    row objects all end up with the same values - that of the last
    'source' array.

    It's something to do with the loop in getSource() because if I replace
    it with source= new Array(i,i) the script behaves correctly. But that
    would be useless for my purposes. Any ideas what the problem could
    be?


    // row constructor
    function rowObject(theso urce)
    {
    this.field=thes ource;
    }

    // return array
    var source=new Array();
    function getSource(i)
    {
    for(j=0;j<2;j++ )
    {
    source[j]=i;
    }
    return source;
    }

    // make objects
    row=new Array();
    for(i=0;i<2;i++ )
    {
    row[i]=new rowObject(getSo urce(i))
    alert(row[0].field[0])
    }
  • Lee

    #2
    Re: Constructor and array argument

    Peter Cartwright said:[color=blue]
    >
    >I'm trying to create an array of row objects containing 'source'
    >arrays, which in the actual script are node values. The problem is the
    >row objects all end up with the same values - that of the last
    >'source' array.
    >
    >It's something to do with the loop in getSource() because if I replace
    >it with source= new Array(i,i) the script behaves correctly. But that
    >would be useless for my purposes. Any ideas what the problem could
    >be?[/color]


    When you have an Array or other Object on the right hand side of
    an assignment operation, the variable is assigned a reference to
    that Object, rather than a full copy, so you've got multiple
    references to a single array.

    Look at the methods of the Array object and use one to make a copy.

    Comment

    Working...