Reputation: 20406
I would expect that after using distances.slice()
, I would have a copy of the array. But when I change an element of the new copy, it still changes the original array. Why?
var distances = [
['-1', '10', '-1', '31'],
['10', '-1', '10', '-1'],
['-1', '-1', '-1', '10'],
['15', '6', '-1', '-1']
];
for (var i = 0; i < 4; i++) {
console.log(distances, 'distances pairstop');
var sampleDistance = distances.slice()
sampleDistance[0][2] = ['fooo']
}
Upvotes: 2
Views: 1170
Reputation: 26161
To clone an array with sub array items with indefinite depth you need a general array cloning tool like;
Array.prototype.clone = function(){
return this.map(e => Array.isArray(e) ? e.clone() : e);
};
So distances.clone()
should just do the job fine.
Upvotes: 1
Reputation: 3985
Slice produces a shallow copy of the array. It says so in the docs:
The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.
Since distances
is an array of arryas, sampleDistance
will be a shallow copy, meaning it will hold refernces to the same 3 (one-dimentional) arrays.
sampleDistance[0][2] = ['fooo']
changes the first one-dimentional array, which is referenced both by sampleDistance
and distances
.
hence your bug.
Upvotes: 5