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? If I delete on c, it mirrors the action on coords. Is this a normal behavior?
Because of the assignment of c, you get the reference of the array coords.
Any change of coords does effect c, until a new value is assigned to 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. When changing one object inside, you are changing the same object with the same reference in 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:
let c = coords.slice();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With