Constructor and array argument

P

Peter Cartwright

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(thesource)
{
this.field=thesource;
}

// 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=new rowObject(getSource(i))
alert(row[0].field[0])
}
 
L

Lee

Peter Cartwright said:
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?


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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top