Skip to content

Instantly share code, notes, and snippets.

@Yunkou
Created April 18, 2016 00:58
Show Gist options
  • Save Yunkou/e7fc6554d9efad93aab9dc2861f4e4e1 to your computer and use it in GitHub Desktop.
Save Yunkou/e7fc6554d9efad93aab9dc2861f4e4e1 to your computer and use it in GitHub Desktop.
/* 复制对象
* @param: obj {JavaScript Object} 原始对象
* @param: isDeep {Boolean} 是否为深拷贝
* @return: {JavaScript Object} 返回一个新的对象
*/
function copy(obj, isDeep) {
var ret = obj.slice ? [] : {}, p;
// 配合 is 函数使用
if(!isDeep && is(obj, 'Array')) return obj.slice();
for(p in obj) {
var prop = obj[p];
if(!obj.hasOwnProperty(p)) continue;
if(is(prop, 'Object') || is(prop, 'Array')) {
ret[p] = copy(prop, isDeep);
} else {
ret[p] = prop;
}
}
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment