Created
January 1, 2014 14:00
-
-
Save lyuehh/8208244 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
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