1. Simple version:
<script type="text/javascript"> const newObj = JSON.parse(JSON.stringify(oldObj)); </script>
Limitations:
He can not be achieved on the cloning function, RegExp and other special object
constructor will abandon objects, all constructors points to the Object
object has a circular reference, will complain
2. Interview edition:
<Script type = "text / JavaScript"> / * * * Deep clone * @param {[type]} subject in need of parent Object cloning * @return {[type]} after deep clone objects * / const clone = parent => { // determine the type const isType = (obj, type) => { IF ( typeof ! obj == "Object") return to false ; const typeString = Object.prototype.toString.call (obj); the let In Flag; Switch (type) { case "Array": flag = typeString === "[object Array]"; break; case "Date": flag = typeString === "[object Date]"; break; case "RegExp": flag = typeString === "[object RegExp]"; break; default: flag = false; } Return In Flag; }; // process the regular const getRegExp = Re => { var the flags = "" ; IF (re.global) the flags + = "G" ; IF (re.ignoreCase) + = the flags "I" ; IF (re.multiline) + = the flags "m" ; return the flags; }; // maintains two arrays to store the circular reference const Parents = []; const Children = []; _clone const = parent => { IF (parent === null ) return null ; IF ( typeof ! parent == "Object") return parent; the let Child, proto; IF (isType (parent, "the Array" )) { / / array special handling child = []; } the else IF (isType (parent, "the RegExp" )) { // for regular special handling objects child =new new the RegExp (parent.source, getRegExp (parent)); IF (parent.lastIndex) child.lastIndex = parent.lastIndex; } the else IF (isType (parent, "Date" )) { // do special processing on the Date object child = new new a Date (parent.getTime ()); } the else { // processed prototype proto = Object.getPrototypeOf (parent); // use the prototype cutting chain Object.create Child = Object.create (proto); } // processing loop reference const index = parents.indexOf (parent); IF (! Index = -1 ) { // has been cited before the parent array exists if the present object description, the object returned directly return Children [index]; } parents.push (parent); children.push (Child); for (the let I in parent) { // recursive Child [I] = _clone (parent [I]); } return Child; }; return _clone (parent ); }; </ script>
Limitations:
Some special cases no treatment: for example Buffer objects, Promise, Set, Map
In addition to ensure that the object is no circular reference, we can cut a special deal on the circular reference, because it is very time consuming