/    Sign up×
Community /Pin to ProfileBookmark

reference type (Array) question

Hello, I am a javascript learner, I have a question to confuse.

[CODE]
var a = [1,2,3];
var b = a;
a[0] = 99;
alert(b);
[/CODE]

The alert output is : 99,2,3

If I really want to copy value of a into b variable, how can I do ?

( I mean, if I want to use copy way, then the alert output can show 1,2,3
how to write the javascript?? or javascript can’t do that ??)

Thanks!

to post a comment
JavaScript

4 Comments(s)

Copy linkTweet thisAlerts:
@toicontienAug 22.2007 — The code you posted is working correctly. Are you wanting to copy the whole array from one variable to another, or do you want to copy just one item from array "a" to array "b"?

To copy one item from one array to the next:
var a = [1,2,3];
var b = [35];
b[1] = a[1];

alert(b); // Shows 35,2
Copy linkTweet thisAlerts:
@Mr_MooAug 22.2007 — <i>
</i>function copyArray(arr) {
var res = [];
for(var i = 0; i &lt; arr.length; ++i) {
res[i] = arr[i];
}
return res;
}
var a = [1,2,3];
var b = copyArray(a);
a[0] = 99;
alert(b);

The function copyArray makes a shallow copy of the array (meaning that if the array contains objects, and you change part of the object in the original array you will also change it in the copied array).
Copy linkTweet thisAlerts:
@KitshingauthorAug 23.2007 — Thanks for toicontien and Mr Moo

~ The answer of Mr Moo is totally meet my request.

Thank a lot~
Copy linkTweet thisAlerts:
@KitshingauthorApr 02.2008 — oh...

This post was almost a year ago,

Anyway, I found another way to copy array at recently.

[CODE]
var a = [1,2,3];
var b = a.slice();
a[0] = 99;
alert(b);
[/CODE]


Using slice() method, that will actually copy one to variable b. ?
×

Success!

Help @Kitshing 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.17,
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,
)...