Skip to content

Instantly share code, notes, and snippets.

@smallnewer
Last active December 22, 2015 21:28
Show Gist options
  • Save smallnewer/6533071 to your computer and use it in GitHub Desktop.
Save smallnewer/6533071 to your computer and use it in GitHub Desktop.
深度克隆。自己写的一个简单的深度克隆,方便。
function deepClone (data) {
var result;
if (isType("Object",data)) {
// 如果是对象
result = {};
var keys = Object.keys(data);
for (var i = 0; i < keys.length; i++) {
var val = data[keys[i]];
result[keys[i]] = _clone(val);
};
}else if (isType("Array",data)) {
// 如果是数组
result = [];
for (var i = 0; i < data.length; i++) {
result[i] = _clone(data[i]);
};
}else{
// 否则可能为str,fn,bool,num,undefined,null
// 或新增的Unit8Array之类。
// 此处全作为基本数据类型处理,因此对fn等复杂数据类型
// 做===判断,会为真。
result = data;
}
function _clone (val) {
var res;
// 如果是对象或者数组,深度克隆
if (isType("object",val) || isType('array',val)) {
res = deepClone(val);
// 否则简单复制
}else{
res = val;
}
return res;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment