js淺拷貝,深拷貝的簡單實現(xiàn)
基礎(chǔ)數(shù)據(jù)
var a = {
num: 1,
arr: [1, 2, 3],
undef: undefined,
nul: null,
str: 'aaa',
fun: function () {
console.log('bbb')
},
json: {
data1: [4, 5],
data2: [6, 8, 9]
}
}
// console.log(JSON.parse(JSON.stringify(a)))
淺拷貝
function simpleClone(obj) {
if (!obj) return null;
var res = obj instanceof Array ? [] : {}
for (let i in obj) {
res[i] = obj[i]
}
return res;
}
// var b = simpleClone(a)
// b.json.data1 = [4, 5, 6]
// console.log(b, a)
// var c = [1, 2, 3]
// console.log(simpleClone(c))
深拷貝
function deepClone(obj) {
if (!obj) return null;
var res = obj instanceof Array ? [] : {}
for (let i in obj) {
res[i] = typeof obj[i] === 'object' ? deepClone(obj[i]) : obj[i]
}
return res;
}
// var c = deepClone(a)
// c.json.data1 = [4, 5, 6]
// console.log(c, a)