

运行结果展示:

归纳:
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))
本文深入探讨了JavaScript中深拷贝与浅拷贝的区别,提供了实现深拷贝的函数,涵盖对象、数组、正则、日期等多种类型,并通过实例展示了拷贝前后数据的变化。
667

被折叠的 条评论
为什么被折叠?



