Merge pull request #1823 from wonderingabout/trick-deep-copy-spread

Trick get a new copy of object/array using spread operator
This commit is contained in:
Peter Roche 2020-03-29 00:19:45 -06:00 committed by GitHub
commit c038ef4669
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -225,6 +225,51 @@ But there's a subtle difference between `Array.from(obj)` and `[...obj]`:
So, for the task of turning something into an array, `Array.from` tends to be more universal.
## Get a new copy of an object/array
Remember when we talked about `Object.assign()` [in the past](https://javascript.info/symbol#symbols-are-skipped-by-for-in)?
It is possible to do the same thing with the spread operator!
```
let arr = [1, 2, 3];
let arrCopy = [...arr]; // spread the array into a list of parameters
// then put the result into a new array
// do the arrays have the same contents?
alert(JSON.stringify(arr) === JSON.stringify(arrCopy)); // true
// are the arrays equal?
alert(arr === arrCopy); // false (not same reference)
// modifying our initial array does not modify the copy:
arr.push(4);
alert(arr); // 1, 2, 3, 4
alert(arrCopy); // 1, 2, 3
```
Note that it is possible to do the same thing to make a copy of an object:
```
let obj = { a: 1, b: 2, c: 3 };
let objCopy = { ...obj }; // spread the object into a list of parameters
// then return the result in a new object
// do the objects have the same contents?
alert(JSON.stringify(obj) === JSON.stringify(objCopy)); // true
// are the objects equal?
alert(obj === objCopy); // false (not same reference)
// modifying our initial object does not modify the copy:
obj.d = 4;
alert(JSON.stringify(obj)); // {"a":1,"b":2,"c":3,"d":4}
alert(JSON.stringify(objCopy)); // {"a":1,"b":2,"c":3}
```
This way of copying an object is much shorter than `let objCopy = Object.assign({}, obj);` or for an array `let arrCopy = Object.assign([], arr);` so we prefer to use it whenever we can.
## Summary
When we see `"..."` in the code, it is either rest parameters or the spread syntax.