Reputation: 7457
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?
Upvotes: 1
Views: 195
Reputation: 3984
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);
Upvotes: 2