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

1
  • Turns out, if I simply do "var array2 = array1.splice();" This makes it independent. Cannot believe I never knew this... Commented Aug 18, 2011 at 17:28

3 Answers 3

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!
Sign up to request clarification or add additional context in comments.

1 Comment

good job; this is ther right way to do this. see --> w3schools.com/jsref/jsref_concat_array.asp
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.

2 Comments

clone() is not a native javascript function.
array.clone is not a Javascript built-in, it's provided by Mootools in your example.
-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();

1 Comment

don't extend Object.prototype --> erik.eae.net/archives/2005/06/06/22.13.54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.