0

I'm working on a larger project, and I've encountered trouble with arrays, demonstrated below.

var x = new Array();
x = [5, 2];
function doStuff(a){
    a[0]++;
    console.log(a);//Prints [6, 2]
}
doStuff(x);
console.log(x);//Prints [6, 2] when it should print [5, 2]

How could I do things with an array passed to a function without modifying the original?

1 Answers1

0

What you're passing to doStuff is a reference to the array. You're not actually passing the data.

You're going to have to explicitly copy the array, in order not to modify the source:

var x = [5, 2];         // No need to use the `Array` constructor.

function doStuff(a) {
    var x = a.slice(0); // Copy the array.
    x[0]++;
    console.log(x);     // Prints [6, 2]
}
doStuff(x);
console.log(x);         // Prints [5, 2]
Cerbrus
  • 70,800
  • 18
  • 132
  • 147