針對js中的各種數(shù)據(jù)類型(String, Number, Boolean, Array, Object)進(jìn)行深度拷貝:
function clone(obj){
var type = typeof (obj);
if (type === "string" || type === "boolean" || type === "number") {
var newone = obj;
} else if (type === "object") {
if (obj === null) {
var newone = null;
} else if (Object.prototype.toString.call(obj).slice(8,-1) === "Array") {
// Object.prototype.toString.call([1,2,3])的返回值為"[object Array]"
var newone = [];
for (var i=0; i<obj.length; i++) {
newone.push(clone(obj[i]));
}
} else if (Object.prototype.toString.call(obj).slice(8,-1) === "Object") {
var newone = {};
for (var i in obj) {
newone[i] = clone(obj[i]);
}
}
}
return newone;
}
**
注意 Object.prototype.toString.call(obj)
用法