Plain JS Flashcards

1
Q

Shallow copy array:

A

=array.slice();
=[…array];
=Array.from(array);
Object.assign([], array);

For deeply nested array or object, we need deep copy

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Deep copy

A
const obj = /* ... */;
const copy = JSON.parse(JSON.stringify(obj));
Can’t use for cyclic objects, also things like Maps, Sets, RegExps, Dates, ArrayBuffers and other built-in types just get lost at serialization. If don’t care these downsides, this way is the best method. 

Otherwise, use the following function:

function structuralClone(obj) {
  return new Promise(resolve => {
    const {port1, port2} = new MessageChannel();
    port2.onmessage = ev => resolve(ev.data);
    port1.postMessage(obj);
  });
}
const obj = /* ... */;
const clone = await structuralClone(obj);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly