/    Sign up×
Community /Pin to ProfileBookmark

how to avoid array pop effect ?

How can i avoid the array’s pop effect that executes pop on array1 too ?

[CODE]<script type=”text/javascript”>
var array1 = new Array() ;
var array2 = new Array() ;
array1[0] = ‘foo’ ;
array1[1] = ‘miao’ ;
array1[2] = ‘grrr’ ;
array2 = array1 ;
array2.pop() ;
alert ( array1 ) ;
alert ( array2 ) ;
</script>[/CODE]

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@konithomimoFeb 08.2007 — Well, you will always get that problem if you set them equal. To fix it you can populate array2 with a simple for loop:

for(var i=0;i&lt;array1.length;i++)
array2[i] = array1[i];


Which makes the entire code:

&lt;script type="text/javascript"&gt;
var array1 = new Array() ;
var array2 = new Array() ;
array1[0] = 'foo' ;
array1[1] = 'miao' ;
array1[2] = 'grrr' ;
for(var i=0;i&lt;array1.length;i++)
array2[i] = array1[i];

array2.pop() ;
alert ( array1 ) ;
alert ( array2 ) ;
&lt;/script&gt;
Copy linkTweet thisAlerts:
@gil_davisFeb 08.2007 — This is rather silly, but effective:
<i>
</i>var array1 = new Array() ;
var array2 = new Array() ;
array1[0] = 'foo' ;
array1[1] = 'miao' ;
array1[2] = 'grrr' ;
[color=red]//[/color]array2 = array1 ;
[color=red]var t = array1.join("~");
array2 = t.split("~");[/color]
array2.pop() ;
alert ( array1 ) ;
alert ( array2 ) ;
Copy linkTweet thisAlerts:
@aQuosauthorFeb 08.2007 — nice! thanks!!
×

Success!

Help @aQuos 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.16,
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,
)...