Vue js recursively clone deep copy object copy array

illustrate

The project encountered a problem. When creating an object, there is a Date field in it. When formatting the Date, because it is passed by reference, the original object will be changed. I thought of deep copying the object, so that it will be in the memory address Zhongxin opens up a space, which is a completely new object.

The js code is as follows:

// 递归深拷贝
export default function copyObj (obj = {
     
     }) {
    
    
  let newobj = null;

  //判断是否需要继续进行递归
  if (typeof (obj) == 'object' && obj !== null) {
    
    
    newobj = obj instanceof Array ? [] : {
    
    };                //进行下一层递归克隆
    for (var i in obj) {
    
    
      newobj[i] = copyObj(obj[i])
    }                //如果不是对象直接赋值
  } else newobj = obj;
  return newobj;
}

Guess you like

Origin blog.csdn.net/qq_43813351/article/details/129487215