复制数组的JavaScript拼接 [英] duplicating arrays javascript splicing
问题描述
我所遇到的一个奇怪的错误在我的code和我不明白为什么会发生。
I have come across a strange bug in my code and I cannot understand why it happens.
我有一个数组数组1。我通过数组2等于ARRAY1复制数组1。然后我修改使用数组2剪接增加号码。 ARRAY1不应该被感动?但是,这两个输出相同的变化。
I have an array array1. I duplicate array1 by making array2 equal to array1. I then modify array2 using splice to add a number. Array1 should not be touched? But both output the same change.
var array1 = [0,1,2,3,4,5];
var array2 = array1;
array2.splice(1,0,1) //add
console.log(array1);
console.log(array2);
我假设我混淆数组赋值?什么是重复阵列没有发生这种情况的正确方法?
I am assuming I am confusing array assignment? What is the proper way to duplicate arrays without this happening?
干杯
推荐答案
使用 array1.concat()
复制,而不是传递一个参考<$ C $数组C>数组1 :
Use array1.concat()
to duplicate the array instead of passing a reference to array1
:
var array1 = [0,1,2,3,4,5];
var array2 = array1.concat();
array2.splice(1,0,1) //add
console.log(array1);
console.log(array2);
array.concat()
可以连接多个阵列,但是如果你传递一个空的参数,你就有效地串联没事数组:克隆阵列
array.concat()
can concatenate multiple arrays, but if you pass an empty argument, you're effectively concatenating an array with nothing: cloning the array.
请注意,任何数组和对象元素仍然引用:
Note that any array and object elements are still references:
var a = [ [1], 2];
var b = a.concat();
b[0][0] = 0;
console.log(b); // gives 0,2
console.log(c); // gives 0,2 too!
这篇关于复制数组的JavaScript拼接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!