1

I have two arrays here, filling one of them with random numbers:

var arr1 = [1];
var arr2 = [];

function arr1Filler() {
    arr2 = arr1;
    setTimeout(function() {
        for (var i = 0; i < 3; i++) {
            arr1[i] = Math.floor(Math.random()*5);
        }
        console.log('array 1:');
        console.log(arr1);
        console.log('array 2:');
        console.log(arr2);
    }, 500);
}

setInterval(arr1Filler, 1000);

in this example, why these two arrays are always equal. In other words, why I am getting something like this:

array 1:   
[ 3, 0, 1 ]
array 2:   
[ 3, 0, 1 ]
array 1:   
[ 0, 2, 3 ]
array 2:   
[ 0, 2, 3 ]
array 1:   
[ 1, 2, 4 ]
array 2:   
[ 1, 2, 4 ]

instead of a result like this (the last value of array 2 is the new value of array 1):

array 1:
[ 1 ]
array 2:
[ 3, 0, 1 ]
array 1:
[ 3, 0, 1 ]
array 2:
[ 0, 2, 3 ]
array 1:   
[ 0, 2, 3 ]
array 2:   
[ 1, 2, 4 ]

What should I do to get the second result which I expect?

Yar
  • 7,020
  • 11
  • 49
  • 69

1 Answers1

2

They are the same because you set the arrays to the same object here:

arr2 = arr1;

So when you add to arr1, arr2 is always identical. What you want is a copy of arr1. You can use slice to effectively make a copy of an array.

arr2 = arr1.slice();

var arr1 = [1];
var arr2 = [];

function arr1Filler() {
    arr2 = arr1.slice();
    setTimeout(function() {
        for (var i = 0; i < 3; i++) {
            arr1[i] = Math.floor(Math.random()*5);
        }
        console.log('array 1:');
        console.log(arr1);
        console.log('array 2:');
        console.log(arr2);
    }, 500);
}

setInterval(arr1Filler, 1000);
lyjackal
  • 3,984
  • 1
  • 12
  • 25
  • Thanks that worked. can you explain the difference? I'm pretty sure in OOP based languages like java `arr2 = arr1.slice();` means `arr2 = arr1;`. Is this a javascript thing!? – Yar May 24 '15 at 06:40
  • @Hooman - see [Javascript by reference vs. by value](http://stackoverflow.com/questions/6605640/javascript-by-reference-vs-by-value) – jfriend00 May 24 '15 at 06:43
  • You would have the same problem in Java. Variables are just pointers to objects in memory. `arr2 = arr1` means "arr2 points to the same object that arr1 points to". In Java you would have `arr2 = arr1.clone()` instead – lyjackal May 24 '15 at 06:43