问题
I have come across a strange bug in my code and I cannot understand why it happens.
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?
Cheers
回答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()
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!
回答2:
If you are using jQuery you can do:
var array1 = [0,1,2,3,4,5];
var array2 = array1.slice();
array2.splice(1,0,1) //add
console.log(array1);
console.log(array2);
Check out this example.
回答3:
Arrays and objects are copied by reference. Try this:
Object.prototype.clone = function() {
var newObj = (this instanceof Array) ? [] : {};
for (i in this) {
if (i == 'clone') continue;
if (this[i] && typeof this[i] == "object") {
newObj[i] = this[i].clone();
} else newObj[i] = this[i]
} return newObj;
}
var array1 = [0,1,2,3,4,5];
var array2 = array1.clone();
来源:https://stackoverflow.com/questions/7111432/duplicating-arrays-javascript-splicing