浅层克隆
var obj ={
name :'abc',
age : 123,
sex : 'female',
card : ['visa', 'unionpay']
}
var obj1 = {}
function clone(origin, target){
var target = target || {};
for(var prop in origin) {
target[prop] = origin[prop];
}
return target;
}
clone(obj, obj1);
深层克隆
//遍历对象 for(var prop in obj)
//1.判断是不是原始值 typeof() object
//2.判断是数组还是对象 instanceof / toString/consutrutor
//3.建立相应的数组或对象
//递归
function deepClone(origin, target){
var target = target || {},
toStr = Object.prototype.toString,
arrStr = "[object Array]";
for(var prop in origin) {
if(origin.hasOwnProperty(prop)){
if(origin[prop] !== "null" &&
typeof(origin[prop]) == 'object'){
/ if(toStr.call(origin[prop]) == arrStr ){
/ target[prop] = [];
/ }else {
/ target[prop] = {};
/ }
target[prop] = toStr.call(origin[prop]) ==
arrStr ? [] : {};
deepClone(origin[prop], target[prop]);
}else{
target[prop] = origin[prop];
}
}
}
条件判断? 是:否 并且会返回值
var num = 1>0? 2+2 : 1+1; return 4
深浅层克隆区别:浅层克隆只是把引用值得地址复制过来了,两者指向同一房间,如果obj引用值改变,则obj1也改变。而深层克隆是两者各指向两个房间,改变引用值互不影响。
网友评论