Handwritten deep copy
There are several types of JavaScript data, and this is probably one of the most popular questions for an interviewer. There are about seven of them
- Number
- String
- Boolean
- Null
- Undefined
- Symbol
- Object
Well!!!!! Now there should be eight, the future interview will answer eight! BigInt
BigInt is a basic numeric type in JavaScript that can represent integers with arbitrary precision. With BigInt, you can safely store and manipulate large integers, even exceeding the safe integer limit for numbers. BigInt is created by appending n to the end of the integer or by calling the constructor.
Common deep copies are for objects and arrays
If you encounter objects of type Date or regular, the result of using ordinary deep copy may be a little different from what you expect
Parse(json.stringify (object)) doesn’t work. Try writing your own copy instead of using the plugin’s own copy methods.
I may include the type is not very complete, but daily use should be no big problem, I hope to correct
let a = {
"apple": 'apple tree',
"orange": /g/i,
"lemon": ["book", new Date(), /^[0-9]*$/, document.head],
'Avocado': new Date(),
'pear': document.body
}
Copy the code
Take a look at the above source object, is it a bit more complex than ordinary object content, if it is you how to make a deep copy of it?
Directly on the code:
Function deepClone(obj) {// If (typeof obj! == 'object' || obj === null) throw new Error(arguments[0] + ' is not a object'); let newObj = (obj instanceof Array) ? [] : {}; For (const key in obj) {/ / access Object itself attribute the if (Object. The hasOwnProperty. Call (obj, key)) {const element = obj [key]; // Store the original object value if(! NewObj [key]) {if(element instanceof Date) {// Let time = new Date(element.getTime()); NewObj [key] = time; }else if(Element instanceof RegExp) {JSON. Stringify newObj[key] = new RegExp(element); } else if((typeof element === 'object' && element ! == null) && element.nodeType === 1) {//DOM element node {nodeType} // element type --> nodeType // element element --> 1 // attribute attr --> 2 // Text text - > 3 / / comment comments -- -- > 8 / / document document dom = > 9 let the document. The getElementsByTagName (element. The nodeName) [0]; newObj[key] = dom; } else { newObj[key] = typeof element === 'object' && element ! == null ? deepClone(element) : element; } } } } return newObj; } let a = { "apple": 'apple tree', "orange": /g/i, "lemon": ["book", new Date(), /^[0-9]*$/, document.head], 'Avocado': new Date(), 'pear': document.body, b: null, c: undefined, e: Symbol() } let b = deepClone(a); console.log(a,b);Copy the code