i have an array channel_chunk

var channel = "global/private/user/updates/user_following/publisher_id/subcriber_id";

channel_chunk = channel.split("/"),

and i assign this array to another variable

var new_arr =  channel_chunk ;

the problem is

when i changed

new_arr[0]  = "test";

channel_chunk[0] also becomes test

so i think it is passed by reference when i am assigning , i want to assign channel_chunk by value to new_arr .

i know jQuery.extend will help. but i am using pure JavaScript in this case , so i can not use it , is there a built in function to do this in JavaScript . please help............

share|improve this question

69% accept rate
feedback

2 Answers

up vote 3 down vote accepted

The "official" way to take a (shallow) copy of (part of) an array is .slice():

var new_arr = channel_chunk.slice(0);

[ It's called a "shallow" copy because any objects or arrays therein will still refer to the originals, but the array itself is a whole new copy. As you're using string primitives that won't affect you. ]

share|improve this answer
feedback

You will need to create a new array. An easy way to do this is simply concat with no args:

var new_arr = channel_chunk.concat();

Now modifying new_arr will have no effect on channel_chunk.

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.