美文网首页
JS实现对象深度拷贝

JS实现对象深度拷贝

作者: Simon_King | 来源:发表于2019-04-02 00:25 被阅读0次
 // 对象不做function的判断
function deepClone(obj) {
  if(!obj) {
    return obj;
  }

  // 如果传入的数组
  if (Array.isArray(obj)) {
     return obj.map(item => {
      if (Array.isArray(item) || typeof item === 'object') {
        return deepClone(item);
      }
      return item;
    });
  }

  // 如果是对象
  let result = {};
  if (typeof obj === 'object') {
    for (const key in obj) {
      if (Array.isArray(obj[key]) || (typeof obj[key] === 'object')) {
        result [key] = deepClone(obj[key]);
      } else {
        result[key] = obj[key];
      }
    }
  }

  return result;
}

相关文章

网友评论

      本文标题:JS实现对象深度拷贝

      本文链接:https://www.haomeiwen.com/subject/axyibqtx.html