Created
February 22, 2013 09:22
-
-
Save leizongmin/5012011 to your computer and use it in GitHub Desktop.
克隆对象
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 克隆对象 | |
* | |
* @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