简体   繁体   中英

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? 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();

This is happening because c and coords now reference the same object. To prevent this, use let c = coords.slice() to create a copy of coords and assign it to 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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM