简体   繁体   中英

how to assign an array by value to another variable javascript

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM