Skip to content

Instantly share code, notes, and snippets.

@xhsdnn
Created March 5, 2018 01:24
Show Gist options
  • Save xhsdnn/7a2d89885dd353ea3574f37148f7f945 to your computer and use it in GitHub Desktop.
Save xhsdnn/7a2d89885dd353ea3574f37148f7f945 to your computer and use it in GitHub Desktop.
function clone(obj) {
if ((typeof (obj) == "object") && (obj != null)) {
if (obj instanceof Array) {
//如果是Array
let newObj = [];
for (let i = 0; i < obj.length; i++) {
if (typeof (obj[i]) == "object") {
newObj[i] = clone(obj[i]);
} else {
newObj[i] = obj[i];
}
}
return newObj;
} else {
//如果是Object
let newObj = {};
for (let i in obj) {
if (typeof (obj[i]) == "object") {
newObj[i] = clone(obj[i]);
} else {
newObj[i] = obj[i];
}
}
return newObj;
}
} else {
return obj;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment