/    Sign up×
Community /Pin to ProfileBookmark

Copying arrays in javascript: by value or by reference???

I am trying to make an array, then make a backup of it before modification by copying it. When i do this everytime i modify the original the backup changes as well. It seems as though i am referencing it by ‘reference’ and not by value. I am doing a straight object copy like so:

myArrayBackup = myArrayOriginal;

To get around this i have create a function to loop through and copy cell by cell. Although this seems to work it is highly inefficient as my script does this action alot.

2 questions:

1) Why can’t i do a straight object copy like above?

2) Is there a better way to do this than looping through and copying each cell?

jason

to post a comment
JavaScript

12 Comments(s)

Copy linkTweet thisAlerts:
@Jeff_MottNov 03.2003 — It seems as though i am referencing it by 'reference' and not by value[/quote]That's because you are.I am doing a straight object copy like so:

myArrayBackup = myArrayOriginal;[/quote]
This will copy the reference, not the object. So now you have two variables that point to the same array.2) Is there a better way to do this than looping through and copying each cell?[/quote]The toSource() method would be the best choice, but IE has yet to implement it. So all you can do is copy everything from one array to another. Although, if the array is multidimensional then that won't even be enough.
Copy linkTweet thisAlerts:
@CharlesNov 04.2003 — [font=monospace]<script type="text/javascript">

<!--

Object.prototype.clone = function () {var o = new Object(); for (var property in this) {o[property] = typeof (this[property]) == 'object' ? this[property].clone() : this[property]} return o}

Array.prototype.clone = function () {var a = new Array(); for (var property in this) {a[property] = typeof (this[property]) == 'object' ? this[property].clone() : this[property]} return a}

a = ['fee', 'fie', 'foe', 'fum', {giant:'says'}];

b = a.clone();

a[4].giant = 'foo';

alert(b[4].giant);

// -->

</script>[/font]
Copy linkTweet thisAlerts:
@Jeff_MottNov 04.2003 — Nice. But why define clone twice? Array will automatically inherit the method from Object.
Copy linkTweet thisAlerts:
@CharlesNov 04.2003 — [i]Originally posted by Jeff Mott [/i]

[B]Nice. But why define clone twice? Array will automatically inherit the method from Object. [/B][/QUOTE]
[font=georgia]Yes, but then the method, as I have written it, would return an Object and not an Array.[/font]
Copy linkTweet thisAlerts:
@jayman_911authorNov 04.2003 — That code seems to work nicely! I'm not exactly sure what is happening in the 'object.prototype.clone....' and 'array.prototype.clone...' code sections as perhaps that is a bit advanced for me at the moment, but as long as it works it's fine by me! ?

If someone feels like giving a quick breakdown of what is going on there i'd greatly appreciate!

Thanx.

jay
Copy linkTweet thisAlerts:
@jayman_911authorNov 05.2003 — Anyway to make this work for a 2 dimensional array? My attempts at making it multidimensonal failed.

jay
Copy linkTweet thisAlerts:
@CharlesNov 05.2003 — [font=monospace]<script type="text/javascript">

<!--

Object.prototype.clone = function () {var o = new Object(); for (var property in this) {o[property] = typeof (this[property]) == 'object' ? this[property].clone() : this[property]} return o}

Array.prototype.clone = function () {var a = new Array(); for (var property in this) {a[property] = typeof (this[property]) == 'object' ? this[property].clone() : this[property]} return a}

a = ['fee', 'fie', 'foe', 'fum',[1, 2, 3, 4]];

b = a.clone();

a[4][1] = 'foo';

alert(b[4][1]);

// -->

</script>[/font]
Copy linkTweet thisAlerts:
@RicardoCasqueteJul 29.2009 — On our case we are trying to clone some Yahoo YUI objects and the two clone methods works, however it takes like 2/3 seconds now to display a right click menu...

so in our case is not an option.

Performs better (although is a pain in the a**) recreate the object property by property. ?

Thanks for the post anyway
Copy linkTweet thisAlerts:
@Angry_Black_ManJul 29.2009 — is this any faster?

&lt;script&gt;
arr1 = [[],{},"string",1]
alert("arr1 = " +arr1)
[COLOR="green"]arr2 = arr1.slice(0, arr1.length)[/COLOR] // native &amp; preserves objects
alert("copied arr1 into arr2 by assigning it the return of the slice from arr1")
alert("arr2 = " + arr2)
arr1.splice(0, 1)
alert("arr1 now = " + arr1)
alert("arr2 = " + arr2)
alert("are arr1 and arr2 the same object? " + (arr1 === arr2)) // this still evaluates to false even if you dont modify arr1 in any way
&lt;/script&gt;
Copy linkTweet thisAlerts:
@Angry_Black_ManJul 29.2009 — also, apparently you don't need to pass any arguments to slice...

its a nice example site, but they can't spell
Copy linkTweet thisAlerts:
@RicardoCasqueteJul 29.2009 — Hi Aaron

thanks for your post!!!!, It just works fast and nice.

However if I call slice without passing any parameters I am still having the issue of having of making a copy by Reference.

[CODE]

currentItems = menuItems.slice ( 0, menuItems.length );
menuItems.splice ( 0, 1 );
[/CODE]


Ricardo Casquete
Copy linkTweet thisAlerts:
@Angry_Black_ManJul 29.2009 — incidentally, the only reason i did a splice was to modify the original so you could see one didn't affect the other.

glad things worked out, and thanks for the clarification on splice w/o arguments
×

Success!

Help @jayman_911 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...