Skip to content

简易deepClone #7

Description

@lvleihere

简易深克隆, 没考虑Date、Regexp、Error

  • 确定你的原始数据对象中的属性值没有 function 或者 undefined, 你可以使用常规的 JSON.parse(JSON.stringify()) 进行深克隆。
/**
 * 简易深度克隆
 * @param {*} originVal - 原始数据
 */
const deepClone = originVal => {
    if (typeof originVal !== 'object') {
        return originVal;
    }
    const hasDeepCloned = originVal.constructor === Object ? {} : [];
    for (const key in originVal) {
        if (originVal.hasOwnProperty(key)) {
            const val = originVal[key];
            hasDeepCloned[key] = typeof val === 'object' ? deepClone(val) : val;
        }
    }
    return hasDeepCloned;
}


const originData = {
    name: 'thunder',
    favor: [{
        one: 'ball'
    }]
};

const newData = deepClone(originData);
newData.name = 'modified data';
newData.favor[0].one = 'modified ball';

console.log(originData); // { name: 'thunder', favor: [ { one: 'ball' } ] }
console.log(newData); // { name: 'modified data', favor: [ { one: 'modified ball' } ] }

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions