转自:https://www.cnblogs.com/embrace-ly/p/10693035.html

方法一:递归

let cloneObj = function(obj){
    let str, newobj = obj.constructor === Array ? [] : {};
    if(typeof obj !== 'object'){
        return;
    } else if(window.JSON){
        str = JSON.stringify(obj), //系列化对象
        newobj = JSON.parse(str); //还原
    } else {
        for(var i in obj){
            newobj[i] = typeof obj[i] === 'object' ?  cloneObj(obj[i]) : obj[i]; 
        }
    }
    return newobj;
};

let arr2 = cloneObj(arr1);

方法二:通过JSON解析解决

let arr2 = JSON.parse(JSON.stringify(arr1));

注意:这种方法拷贝后的数组会丢失原数组中定义的方法和数组原型中定义的方法。

相关文章:

  • 2021-12-30
  • 2021-11-22
  • 2022-12-23
  • 2021-12-27
  • 2021-04-20
  • 2022-12-23
  • 2021-10-08
  • 2021-04-24
猜你喜欢
  • 2022-12-23
  • 2021-06-10
  • 2022-12-23
  • 2022-12-23
  • 2021-06-06
  • 2022-12-23
相关资源
相似解决方案