JavaScript深拷贝

本文深入探讨了JavaScript中深拷贝与浅拷贝的区别,提供了实现深拷贝的函数,涵盖对象、数组、正则、日期等多种类型,并通过实例展示了拷贝前后数据的变化。

运行结果展示:

归纳:

1.concat也能实现深拷贝,但是只能拷贝一层,对于嵌套数组里面的值无法修改

2.判断数组的方法

(1)Array.isArray(arr)  

(2)arr.constructor == Array  (注意:两个等号,且没有引号)

(3)obj instanceof Array

3.深拷贝和浅拷贝还有其他方法,但是上面的是通用方法

2021-10-22  记录一道蚂蚁的前端笔试题

实现一个深拷贝函数,需要实现以下对象、数组、正则、日期等深拷贝

var obj={
        str:'abc',
        time:new Date(),
        reg:/123/,
        nodeParent:document.body,
        job:{
            jobStr:'cdf',
            jobTime:new Date(),
            jobNode:document.body,
            jobArr:[new Date(),/123/]
        },
        list:['abc',/123/i,new Date(),document.body,{a:123},[1,/23/g]]
    }

   



function deepClone (obj){
    // debugger
    // let newObj=obj instanceof Array?[]:{}
    let newObj=null
    let type = Object.prototype.toString.call(obj) 

    if(type === '[object Object]') {
        for(let i in obj) {
            if(typeof obj[i] !== 'object') {
                newObj[i] = obj[i]
            }else{
                newObj[i] = deepClone(obj[i])
            }
        }
    }else if(type === '[object Array]') {
        obj.forEach((item,index)=>{
            if(typeof item !== 'object') {
                newObj[index] = item
            }else{
                newObj[index] = deepClone(obj[index])
            }
        })

    }else if(type === '[object Date]') {
        newObj = new Date(obj)
    }else if(type === '[object RegExp]') {
        var reFlags = /\w*$/;
        newObj = new obj.constructor(obj.source, reFlags.exec(obj));
        newObj.lastIndex = obj.lastIndex;
    }else if(obj instanceof HTMLElement && obj.nodeType ==1) {
        newObj = obj.cloneNode(true)
    }
    return newObj;
}

console.log('原来是:',obj)
console.log('答案是:',deepClone(obj))

obj.list = ['a',new Date(),document]

console.log('原来是:',obj)
console.log('答案是:',deepClone(obj))

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值