判斷是否是原始值 使用方法:typeof()/object javascript
判斷是數組仍是對象 使用方法: instanceof toString constructorjava
創建相應的數組或對象數組
循環遞歸bash
function deepClone(origin,target){
var target = target || {},
toStr = Object.prototype.toString,
arr = "[object Array]";
for(var prop in origin){
if(origin.hasOwnProperty(prop)){ //選擇本身的屬性
if(origin[prop] !== 'null' && typeof(origin[prop]) == 'object'){//區分原始值和引用值
if(toStr.call(origin[prop]) == arr){//區分數組和對象
target[prop] = [];//創建數組
}else{
target[prop] = {};//創建對象
}
deepClone(origin[prop],target[prop]); //循環遞歸
}else{
target[prop] = origin[prop];
}
}
}
return target;
}複製代碼
target[prop] = (toStr.call(origin[prop]) == arr) ? [] : {};
ui
function deepClone(origin,target){
var target = target || {},//容錯
toStr = Object.prototype.toString,//.call
arr = "[object Array]";//數組原型
for(var prop in origin){
if(origin.hasOwnProperty(prop)){//判斷是不是本身的屬性
if(origin[prop] !== 'null' && typeof(origin[prop]) == 'object'){//判斷引用值仍是原始值
target[prop] = (toStr.call(origin[prop]) == arr) ? [] : {};//判斷是數組仍是對象 而後相應創建數組/對象
deepClone(origin[prop], target[prop]);//循環遞歸
}else{//原始值
target[prop] = origin[prop];
}
}
}
return target;
}複製代碼
var obj1 = {
name : 'sunny',
age : 100,
sayName : function(){
console.log(this.name);
}
}
var obj2 = {};複製代碼
執行拷貝this
deepClone(obj1, obj2);//放入源對象和拷貝對象複製代碼