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