2021.7.22 封装数组和对象的深浅合并

// 自定义可以用于数组和对象上门的each方法
const each = function each(obj, callback) {
  if (obj == null || typeof obj !== "object") throw new TypeError("obj must be an array/like-array/object");
  if (typeof callback !== "function") callback = function () {
  };
  if (Array.isArray(obj)) {
    let i = 0,
      length = obj.length,
      item;
    for (; i < length; i++) {
      item = obj[i];
      if (callback.call(item, item, i) === false) break;
    }
  } else {
    let keys = Object.keys(obj),
      i = 0,
      length = keys.length,
      key,
      item;
    if (typeof Symbol !== "undefined") keys = keys.concat(Object.getOwnPropertySymbols(obj));
    for (; i < length; i++) {
      key = keys[i];
      item = obj[key];
      if (callback.call(item, item, key) === false) break;
    }
  }
  return obj;
}

// 封装深浅合并
const merge = function merge() {
  let options,
    target = arguments[0] || {},
    i = 1,
    length = arguments.length,
    deep = false,
    treated = arguments[length - 1];
  if (typeof target === "boolean") {
    deep = target;
    target = arguments[i] || {};
    i++;
  }
  if(Array.isArray(treated) && treated.treated) {
    length--;
  } else {
    treated = [];
    treated.treated = true;
  }
  if(typeof target !== "object" && typeof target !== "function") target = {};
  for(; i<length;i++){
    options = arguments[i];
    if(options ==null) continue;
    if(treated.includes(options)) return options;
    treated.push(options);
    each(options, function(copy, name){
      let copyIsArray = Array.isArray(copy),
        copyIsObject = typeof copy === "object",
        clone = target[name];
      if(deep && copy && (copyIsArray || copyIsObject)) {
        if(copyIsArray && !Array.isArray(clone)) clone = [];
        if(copyIsArray && (typeof clone !== "object")) clone = {};
        target[name] = merge(deep, clone, copy, treated);
      } else if(copy !== undefined) {
        target[name] = copy;
      }
    });
  }
  return target;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值