Array and Object Assignment

Photoshop Script Snippets - Note: Full Scripts go in the Photoshop Scripts Forum

Moderators: Kukurykus, Tom, xbytor

Andrew

Array and Object Assignment

Post by Andrew »

In short when you assign one object or array variable to another (eg array1 = array2) an action performed subsequently on one object is carried through to the other object - or to put it differently, both variables reference the same underlying content.

This probably falls into the category of why admit one's ignorance but I am amazed to have only just discovered it. I do remember reading something about it with another language but I have never noticed it with JS until today.

Code: Select allarray1 = [1,2,3,4];
array2 = array1;
alert(array1+'  '+array2);
// returns 1,2,3,4 1,2,3,4

array1.pop();
alert(array1+'  '+array2);
// returns 1,2,3 1,2,3

array2.pop();
alert(array1+'  '+array2);
// returns 1,2 1,2

array1[0]='its new';
alert(array1+'  '+array2);
// returns its new,2 its new,2

array2[1]='to me!';
alert(array1+'  '+array2);
// returns its new, to me! its new, to me!

myObj = {p1: 'one',p2: 'two'};
newObj = myObj;
alert(myObj.toSource()+'  '+newObj.toSource());
 // returns ({p1: 'one',p2: 'two'})  ({p1: 'one',p2: 'two'})

newObj.p1 = 'new';
myObj.p2 = 'too!';
alert(myObj.toSource()+'  '+newObj.toSource());
// returns {p1: 'new',p2: 'too!'}  {p1: 'new',p2: 'too!'}

Andrew

Array and Object Assignment

Post by Andrew »

To make the assigned variables independent you can use:

Code: Select allarray2 = array1.toString().split(',');

newObj = eval(myObj.toSource());

xbytor

Array and Object Assignment

Post by xbytor »

To simply copy an array, try

array2 = array1.slice(0);

Copying the underlying objects would require serializing and deserializing the entire array. This is possible with the new Reflection apis in CS2. It just not for the faint of heart.