Skip to content

Instantly share code, notes, and snippets.

@leizongmin
Created February 22, 2013 09:22
Show Gist options
  • Save leizongmin/5012011 to your computer and use it in GitHub Desktop.
Save leizongmin/5012011 to your computer and use it in GitHub Desktop.
克隆对象
/**
* 克隆对象
*
* @param {Object} obj
* @return {Object}
*/
var clone = function (obj) {
var seen = [];
var cloneObj = function (obj) {
if (typeof(obj) === 'object') {
if (obj === null) {
return obj;
} else {
// 为避免死循环,不再克隆已经出现过的对象
if (seen.indexOf(obj) !== -1) {
return obj;
} else {
seen.push(obj);
var ret = {};
for (var i in obj) {
ret[i] = cloneObj(obj[i]);
}
return ret;
}
}
} else {
return obj;
}
};
return cloneObj(obj);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment