vant 源码解析 之深层 合并对象 深拷贝

源码

将两对象的属性合并,深层对象也可以

function isDef(value: any): boolean {
    // value:any 表示传入的参数是任意类型  boolean 表示返回值是boolean类型
    return value !== undefined && value !== null;
    // 传入的值不能是undefined 也不能是null
}
//  in 15.686s  0.486s

function isObj(x: any): boolean {
    debugger
    //判断一个值是否是 对象类型
    // 传入的参数 是 any 任意类型i
    // 返回值是 boolean
    const type = typeof x;
    // typeof 判断数据类型
    // typeof 判断数据类型时 null 也是 object 所以 type 不能为null
    // 函数也是 对象
    return x !== null && (type === 'object' || type === 'function');
}
const { hasOwnProperty } = Object.prototype;
//判断对象是否包含某个属性(不包含对象原型上的属性)
type objectType = {
    [key: string]: any;
}
function assignKey(to: objectType, from: objectType, key: string) {
    const val = from[key];
    // 拿到老的数据的 某个key的值

    if (!isDef(val)) {// 当前key对应的 老数据的值 是undefined就return
        return;
    }

    if (!hasOwnProperty.call(to, key) || !isObj(val)) {
        // 如果目标对象的 这个key 不存在就 老数据对应的key值 赋值给 目标对象to
        to[key] = val;
    } else {
        to[key] = deepAssign(Object(to[key]), from[key]);
    }
}

function deepAssign(to: objectType, from: objectType) {
    Object.keys(from).forEach(key => {
        assignKey(to, from, key);
    });

    return to;
}

测试

let toInfo={
    name:"123",
    age:'16',
    more:{
        hobby:'打篮球',
        address:'合肥'
    },
    color:'red'
}
let fromInfo={
    name:"12343553",
    age:'16545353',
    more:{
        hobby:'打篮球5353',
        address:'合肥5353'
    },
    sex:'男'
}
let result: objectType = deepAssign(toInfo,fromInfo)
console.log("result",result)

深拷贝

import { deepAssign } from './deep-assign';

export function deepClone(obj: object): object {
  if (Array.isArray(obj)) {
    return obj.map(item => deepClone(item));
  }
  if (typeof obj === 'object') {
    return deepAssign({}, obj);
  }
  return obj;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值