js实现深拷贝

辰漪
2021-12-24 / 0 评论 / 89 阅读 / 正在检测是否收录...

1. 使用递归

let str = "我是string基本数据类型"
let arr = [1, 6, [1, 3, 5, 7, 9], 5, 8, { a: 4, b: 7 }, 9, 0]
let obj = { a: 1, b: 2, c: 3, d: [123, 456], e: { ea: 789, eb: 666 } }
let nu = null
function deepClone(ob) {
    if (typeof ob === "object") {
        if (Object.prototype.toString.call(ob).slice(8, -1) === 'Null') return ob
        if (ob instanceof Array) {
            // 数组
            let newArr = []
            ob.forEach((item, index, arr) => {
                newArr[index] = deepClone(item)
            })
            return newArr
        } else {
            // 对象
            let newObj = {}
            // for (let k in ob) {
            //  newObj[k] = deepClone(ob[k])
            // }
            Object.keys(ob).forEach((key, index, arr) => {
                newObj[key] = deepClone(ob[key])
            })
            return newObj
        }
    } else {
        return ob
    }
}
console.log(deepClone(str))
console.log(deepClone(arr))
console.log(deepClone(obj))
console.log(deepClone(nu))

2. JSON.parse()和JSON.stringify()

JSON.stringify() // 将对象转化为json字符串
JSON.parse() // 将json转化为json对象
console.log(JSON.parse(JSON.stringify({a: 1, b: [4,5,6]})))

该方法可能会出现如下问题

  1. undefined、任意的函数以及 symbol 值,在序列化过程中会被忽略
  2. Date 日期调用了 toJSON() 将其转换为了 string 字符串(Date.toISOString()),因此会被当做字符串处理。
  3. NaN 和 Infinity 格式的数值及 null 都会被当做 null。
  4. 其他类型的对象,包括 Map/Set/WeakMap/WeakSet,仅会序列化可枚举的属性。
  5. 对包含循环引用的对象(对象之间相互引用,形成无限循环)执行此方法,会抛出错误。
    请谨慎使用

3. Object.assign() (该方法只能浅拷贝)

1
选择打赏方式:
微信

评论 (0)

取消