0

I'm trying to pass a global defined array as an argument to a function. I thougt this function would treat the argument as a local variable. But it doesn't... Changing the (in my opinion) local variable also changes the values of the global array. What am I doing wrong?

clickX = [];
for(var i=0; i<10; i++) {
    clickX[i] = i;
}
doThis(clickX);

function doThis(x) {
    for(var i=0; i<x.length; i++) {
        x[i]++;
        alert(clickX[i]); // this alerts the changed value of x[i] and not the origin value of the global array
    }
}

jsfiddle: https://jsfiddle.net/n546rq89/

Henning
  • 33
  • 4
  • 2
    Objects are passed by reference in JS. (`var x = [1,2,3]; var y = x; y.splice(0, 1); console.log(y); //[2, 3]`) – tymeJV Jul 21 '15 at 21:05
  • You're not changing the variable (which is indeed local, as you can confirm by `x = []`), you're changing the object (by modifying the properties of it). – Bergi Jul 21 '15 at 21:07
  • Thanks, not it's getting clearer. How can I change values of the object in the function without changing the origin object? Somehow duplicate it? – Henning Jul 21 '15 at 21:08
  • See my answer for how to pass by value. – GPicazo Jul 21 '15 at 21:09
  • @Henning: yes, you have to create a new object that you then pass. – Bergi Jul 21 '15 at 21:10
  • Understood and fixed my problem, thank you very much! – Henning Jul 21 '15 at 21:22
  • My opinion to the duplicate answer: The solution is the same, but I wouldn't have found it because I thougt my problem would be associated with the circumstance off the function and the argument. Same solution, but different problem. – Henning Jul 21 '15 at 21:26

1 Answers1

0

In Javascript, arrays are passed by reference by default. You can alternatively pass ARRAY.slice() to pass by value:

clickX = [];
for(var i=0; i<10; i++) {
    clickX[i] = i;
}
doThis(clickX.slice());

function doThis(x) {
    for(var i=0; i<x.length; i++) {
        x[i]++;
        alert(clickX[i]); // this alerts the changed value of x[i] and not the origin value of the global array
    }
}

Look at this thread for an explanation of slice() and copying array in JS.

Community
  • 1
  • 1
GPicazo
  • 6,516
  • 3
  • 21
  • 24