This time I will show you how to use the clone() function of JS. What are the precautions for using the clone() function of JS?The following is a practical case, let’s take a look.
1. Solve the problem codefunction clone(obj){ var copy; switch(typeof obj){ case 'undefined':break; case 'number': case 'string': case 'boolean': case 'function':copy = obj;break; case 'object': if(obj == null) copy = null; else if(toString.call(obj) === '[object Array]') { copy = []; for(var i in obj) copy.push(clone(obj[i])); } else if(toString.call(obj) === '[object RegExp]') { copy = obj; } else { copy = {}; for(var j in obj) copy[j]= clone(obj[j]); } } return copy; } var a=undefined; var b=1; var c="Hello"; var d=true; var add=function(a,b){ return a+b; } var e=null; var f=[1,2,3]; var g=/^\s+/; var h={ a:1, b:2 } console.log(typeof clone(a)); console.log(typeof clone(b)); console.log(typeof clone(c)); console.log(typeof clone(d)); console.log(clone(add)(1,2)); console.log(Object.prototype.toString.call(clone(e))); console.log(Object.prototype.toString.call(clone(f))); console.log(Object.prototype.toString.call(clone(g))); console.log(Object.prototype.toString.call(clone(h)));
. What should I do? Regular expression , null, The typeof of object are all . Looking at the above code, it is solved using Object.prototype.toString.call(obj) or toString.call(obj).
Then why not use obj.toString() directly? Let's first take a look at what obj.toString() will output? null and undefined actually went wrong, this is for sure, because toString() cannot complete the transformation of null and undefined, only use String() If String() converts something other than null or undefined, it will be automatically converted to toString(). I’m going too far. . Let’s get back to the topicSo what is the result of using Object.prototype.toString.call(obj)? It’s actually different. What’s going on? It turns out that although Array, Null and other types are instances of Object, they each override the toString() method. Let’s try to verify it:var arr=[1,2,3]; console.log(Array.prototype.hasOwnProperty("toString"));//判断原型中是否有toString()方法console.log(arr.toString());delete Array.prototype.toString;//删除Array原型里面重写的toStringconsole.log(Array.prototype.hasOwnProperty("toString")); console.log(arr.toString());
How text-align realizes both ends alignment
MySQL reset Root password on Mac system
The above is the detailed content of How to use the clone() function of JS. For more information, please follow other related articles on the PHP Chinese website!