1、先写蹦床函数——可以将递归转为循环执行
点击查看代码
//蹦床函数
function toc(func) {
let argsArr = [];
let active = false;
return function () {
argsArr.push(arguments)
if (!active) {
active = true
while (argsArr.length) {
func.apply(this,argsArr.shift())
}
active = false
}
}
}
2、深拷贝的业务逻辑——这里比较难写,因为需要把数据都当参数拿出来,不能使用内部变量,否则有与上一执行栈环境有牵连,就会导致闭包存在
点击查看代码
let deep = toc( function (obj = {}, level = 0, target = {}, curkeys = []) {
let s = 'target'
for(let v of curkeys){
s += `['${v}']`
}
for (let key in obj) {
s += '[key] = '
if (['[object Array]', '[object Object]'].includes(Object.prototype.toString.call(obj[key]))) {
s += `Object.prototype.toString.call(obj['${key}']) === '[object Object]' ? {} : []`
eval(s)
deep(obj[key], level + 1, target, [...curkeys, key])
} else {
s += `obj['${key}']`
eval(s)
}
// console.log(s)
return target
}
})
3、实际调用
点击查看代码
let target1 = {} // 作为入参传入,即是入参,也是出参
let a = deep({
a: [0, 2, 3, 4, [[[[[[[[1]]]]]], {a:[[2,3,3,3,3,44,5,5,5,5,5,5,,,,]]}]]],
b: {
c: 1,
d: {
s: 222
},
xxx: undefined,
null: null
}
}, 0 , target1)
console.log('最终值:', JSON.stringify(target1))
4、执行结果
标签:obj,递归,Object,let,key,蹦床,拷贝 From: https://www.cnblogs.com/MrZhous/p/17043894.html