Implement a function clone to replicate values for 5 major data types in JavaScript, including number, String, Object, Array, Boolean.
1 /** Object Cloning2 * Supports basic data types and objects3 * Recursive method*/ 4 functionClone (obj) {5 varo;6 Switch(typeofobj) { 7 Case"Undefined": 8 Break; 9 Case"string": o = obj + ""; Ten Break; One Case"Number": o = obj-0; A Break; - Case"Boolean": o =obj; - Break; the Case"Object"://object is divided into two cases (objects) or arrays (array) - if(obj = = =NULL) { -o =NULL; -}Else{ + if(Object.prototype.toString.call (obj). Slice (8,-1) = = = = "Array") { -o = []; + for(vari = 0; i < obj.length; i++) { A O.push (Clone (Obj[i)); at } -}Else{ -o = {}; - for(varKinchobj) { -O[K] =Clone (Obj[k]); - } in } - } to Break; + default: o =obj; - Break; the } * returno; $ }Panax Notoginseng - varM1 = Clone ([All]); the varM2 = Clone ({1: ' 1 ', ' Hello ': 32}); +Console.log (M1);//[1, 2, 3] AConsole.log (m2);//{' 1 ': ' 1 ', hello:32}
Expansion: Why use Object.prototype.toString.call (obj) to detect object types? You can refer to this blog post without understanding the function.
Here I mainly explain Object.prototype.toString.call (obj). Slice (8,-1) = = = "Array"? What is the meaning.
Object.prototype.toString.call ([]); // "[Object array]" [Object array] ". Slice (8,-1); // "Array"
In the case of an array object, Object.prototype.toString.call ([]) detects the result of "[Object Array]" and intercepts the substring through the slice method. the Slice () method of the string can be used to view the JS elevation P124
Implement a function clone to copy values from 5 major data types in JavaScript (including number, String, Object, Array, Boolean)