Skip to content

Instantly share code, notes, and snippets.

@lyuehh
Created January 1, 2014 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lyuehh/8208244 to your computer and use it in GitHub Desktop.
Save lyuehh/8208244 to your computer and use it in GitHub Desktop.
function copy(obj) {
// if (Object.prototype.toString.call(obj) !== '[object Object]') {
if (typeof obj !== 'object') {
return;
}
var ret = obj.constructor === Object ? {} : [];
for (var i in obj) {
if (obj[i].constructor === Array) {
ret[i] = Array.prototype.slice.call(obj[i]);
} else if (obj[i].constructor === Object) {
ret[i] = copy(obj[i]);
} else {
ret[i] = obj[i];
}
}
return ret;
}
var a = {
"name": "aa",
"job": {
"a": "b",
"c": "d"
},
"haha": [1,2,3]
};
console.log(a);
console.log(copy(a));
var b = [1,2,3];
console.log(b);
console.log(copy(b));
var c = [{"a":"1"}, {"b":"2"}];
console.log(c);
console.log(copy(c));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment