[英]Why does my original array get spliced if I splice the cloned array in JavaScript?
I have the following code: 我有以下代码:
var coords = [
{lat: 39.57904, lng: -8.98094, type: "a"}, // A
{lat: 39.55436, lng: -8.95493, type: "b"}, // B
{lat: 39.56634, lng: -8.95836, type: "c"} // C
];
var travelingOptions = [];
getAllTravelingOptions();
function getAllTravelingOptions(){
coords.forEach((point, pos) => {
let c = coords;
delete c[pos];
console.log(c);
console.log(coords);
});
}
Why is it that variable c
and coords
are always the same? 为什么变量
c
和coords
总是一样的? If I delete on c
, it mirrors the action on coords
. 如果我在
c
删除,它会反映对coords
的操作。 Is this a normal behavior? 这是正常行为吗?
Because of the assignment of c
, you get the reference of the array coords
. 由于
c
的赋值,你得到了数组coords
的引用。
Any change of coords
does effect c
, until a new value is assigned to c
. 任何
coords
更改都会影响c
,直到为c
分配新值。
If you make a copy of the array with Array.slice
, you get a new array but with the same reference of the objects. 如果使用
Array.slice
数组的副本,则会获得一个新数组,但具有相同的对象引用。 When changing one object inside, you are changing the same object with the same reference in c
. 更改内部的一个对象时,您将使用
c
的相同引用更改同一对象。
var coords = [ {lat: 39.57904, lng: -8.98094, type: "a"}, // A {lat: 39.55436, lng: -8.95493, type: "b"}, // B {lat: 39.56634, lng: -8.95836, type: "c"} // C ], c = coords.slice(); console.log(c); coords[1].type = 'foo'; console.log(c);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Assignment does not clone array it only creates reference to the orginal object/array. 赋值不克隆数组它只创建对原始对象/数组的引用。 You can use Array.prototype.slice() to make a shallow copy:
您可以使用Array.prototype.slice()来生成浅表副本:
let c = coords.slice();
This is happening because c
and coords
now reference the same object. 这是因为
c
和coords
现在引用相同的对象。 To prevent this, use let c = coords.slice()
to create a copy of coords
and assign it to c
. 要防止这种情况,请使用
let c = coords.slice()
创建coords
的副本并将其分配给c
。
let original = [1, 2, 3, 4]; let test = original; let testSlice = original.slice(); original[0] = 12345; console.log('test: ', test) console.log('testSlice: ', testSlice)
However, the new array will still reference the same objects that the old array did. 但是,新数组仍将引用旧数组所执行的相同对象。 A quick fix for this would be 'cloning' these objects.
快速解决这个问题就是“克隆”这些对象。
let objs = [ {'obj': 1}, {'obj': 2}, {'obj': 3} ]; let newArr = []; objs.forEach(obj => { let newObj = {}; Object.keys(obj).forEach(key => { newObj[key] = obj[key]; }); newArr.push(newObj); }); console.log('old: ', objs) console.log('new: ', newArr) newArr[0].obj = 12345; console.log('old after changing obj on new: ', objs)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.