Why variable skopirovana using slice() changes its value?

code:
var array = [
 [-0.04, 0.01, 4],
 [-1.09, 9, 0],
 [8.1, 10.4, 7],
 [15, 6, 3]
];
log("original array");
array.forEach(function(item) {
 log("[" + item + "]")
});
var newArray = [];
newArray = array.slice();
log("copy array");
newArray.forEach(function(item) {
 log("[" + item + "]")
});
newArray.forEach(function(item) {
 item.splice(1, 1)
});
log("modified array");
newArray.forEach(function(item) {
 log("[" + item + "]")
});
log("original array");
array.forEach(function(item) {
 log("[" + item + "]")
});

the result:
original array
[-0.04,0.01,4]
[-1.09,9,0]
[8.1,10.4,7]
[15,6,3]
copy array
[-0.04,0.01,4]
[-1.09,9,0]
[8.1,10.4,7]
[15,6,3]
modified array
[-0.04,4]
[-1.09,0]
[8.1,7]
[15,3]
original array
[-0.04,4]
[-1.09,0]
[8.1,7]
[15,3]

https://jsfiddle.net/Quncore/xrpo5kLb/

--
Thanks for the solution and for the explanation!
made as follows: var newArray = array.map(function(item){return item.slice()})
July 12th 19 at 17:37
2 answers
July 12th 19 at 17:39
Solution
slice returns a new array, you're right, but deep copy he makes. That is, if inside of the array you have an object or array, then the slice will return you a reference to the object from the original array. Use some library for deep copy. Well, or write a crutch that will make a slice in the loop : )
July 12th 19 at 17:41
Decided replacement
var newArray = [];
newArray = array.slice();

on
var newArray = new Array(Array.length);
newArray = array.map(function(item){return item.slice()})

Since this is not a multidimensional array, but an array with arrays, the slice() return the array of pointers to subarrays instead of their values
Actually half the user specifies one, and eventually want more, you'll decide another time, you need to explain or solve - Leslie commented on July 12th 19 at 17:44
Both. The second is more valuable - nicholas_Fadel commented on July 12th 19 at 17:47
: More valuable than your understanding of the issue, and the ability to properly formulate the task. You need to review the values - Leslie commented on July 12th 19 at 17:50

Find more questions by tags JavaScript