[英]how to assign an array by value to another variable javascript
i have an array channel_chunk
我有一个数组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
channel_chunk[0]
也成了test
so i think it is passed by reference when i am assigning , i want to assign channel_chunk
by value to new_arr
. 所以我认为它是在我分配时通过引用传递的,我想按值将channel_chunk
分配给new_arr
。
i know jQuery.extend
will help. 我知道jQuery.extend
会有所帮助。 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 . 但我在这种情况下使用的是纯JavaScript,所以我无法使用它,是否有内置函数在JavaScript中执行此操作。 please help............ 请帮忙............
The "official" way to take a (shallow) copy of (part of) an array is .slice()
: 采用(部分)数组(浅)副本的“官方”方式是.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: 一个简单的方法是简单地连接没有args:
var new_arr = channel_chunk.concat();
Now modifying new_arr will have no effect on channel_chunk. 现在修改new_arr对channel_chunk没有影响。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.