Js 深拷贝,很好理解的方式之一

来源:互联网 发布:西安网络推广价格 编辑:程序博客网 时间:2024/06/08 13:51

即转换为Json字符串,再转换为对象,这边是es6写法:

/** * 深拷贝 * @param obj * @returns {*} */export 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 (let i in obj) {            newobj[i] = typeof obj[i] === 'object' ?                cloneObj(obj[i]) : obj[i];        }    }    return newobj;};
0 0
原创粉丝点击