function getType(data) { return Object.prototype.toString.call(data).replace(']', '').substring(8) } function _clone(data, res) { const type = getType(data) if (type === 'Object') { Object.keys(data).map(i => { if (res[i] === 'Object') { res[i] = _clone(data[i], {}) } else if (res[i] === 'Array') { res[i] = _clone(data[i], []) } else { res[i] = data[i] } }) } else if (type === 'Array') { data.map(i => { const type2 = getType(i) if (type2 === 'Object') { res.push(_clone(i, {})) } else if (type2 === 'Array') { res.push(_clone(i, [])) } else { res.push(i) } }) } else { res = data } return res } function clone(data) { const type = getType(data) if (type === 'Array') { return _clone(data, []) } else if (type === 'Object') { return _clone(data, {}) } else { return data } } const test = { name: '张三', age: 18, login: true, habbies: ['打球', { a: 'javascript', b: ['vue', { [1]: 'react', [2]: 'angule' }] }] } const result1 = clone(test) result1.name = '李四' result1.habbies = '没有兴趣爱好' console.log(test, result1)
标签:递归,res,clone,Object,js,type,拷贝,else,data From: https://www.cnblogs.com/fmg0224/p/18152498