2

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

myol
  • 8,857
  • 19
  • 82
  • 143
  • Turns out, if I simply do "var array2 = array1.splice();" This makes it independent. Cannot believe I never knew this... – myol Aug 18 '11 at 17:28

3 Answers3

4

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!
Lekensteyn
  • 64,486
  • 22
  • 159
  • 192
0

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.

Norman Joyner
  • 955
  • 6
  • 12
-1

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();
AlienWebguy
  • 76,997
  • 17
  • 122
  • 145