Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

深浅拷贝实现 #108

Open
louzhedong opened this issue Dec 14, 2018 · 2 comments
Open

深浅拷贝实现 #108

louzhedong opened this issue Dec 14, 2018 · 2 comments

Comments

@louzhedong
Copy link
Owner

/**
 * 浅拷贝
 *
 * @param {*} obj
 */
var shallowCopy = function (obj) {
  if (typeof obj != 'object') return;
  var newObj = obj instanceof Array ? [] : {};
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      newObj[key] = obj[key]
    }
  }
  return newObj;
}


/**
 * 深拷贝
 *
 * @param {*} obj
 */
var deepCopy = function (obj) {
  if (typeof obj != 'object') return;
  var newObj = obj instanceof Array ? [] : {};
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      newObj[key] = typeof obj[key] == 'object' ? deepCopy(obj[key]) : obj[key];
    }
  }
  return newObj;
} 
@chenbin2015
Copy link

chenbin2015 commented May 19, 2021

这个深拷贝有问题吧,只处理了数组,其他类对象就有问题了,可以试下这个对象

var obj = {
        a: 1,
        b: '2',
        c: {
          cc: 2
        },
        d: function (a) {
          console.log(a)
        },
        e: [1, 2, 3, 4, 5],
        f: undefined,
        g: null,
        h: Symbol('123'),
        i: {
          aa: 11,
          bb: '22',
          cc: {
            ccc: {
              cccc: function (a) {
                console.log(a)
              }
            }
          }
        },
        j: new Date()
      }

@louzhedong
Copy link
Owner Author

这个深拷贝有问题吧,只处理了数组,其他类对象就有问题了,可以试下这个对象

var obj = {
        a: 1,
        b: '2',
        c: {
          cc: 2
        },
        d: function (a) {
          console.log(a)
        },
        e: [1, 2, 3, 4, 5],
        f: undefined,
        g: null,
        h: Symbol('123'),
        i: {
          aa: 11,
          bb: '22',
          cc: {
            ccc: {
              cccc: function (a) {
                console.log(a)
              }
            }
          }
        },
        j: new Date()
      }

这个是不支持的哈~ 只处理了数组和普通的对象~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants