1

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............

2 Answers 2

3

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. ]

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.