zoukankan      html  css  js  c++  java
  • 深拷贝和差集

    function deepClone(obj) {
        let newObj = Array.isArray(obj) ? [] : {}
        if (obj && typeof obj === "object") {
            for (let key in obj) {
                if (obj.hasOwnProperty(key)) {
                    newObj[key] = (obj && typeof obj[key] === 'object') ? deepClone(obj[key]) : obj[key];
                }
            }
        }
        return newObj
    }

    功能较为完整

    function deepClone(target,cache = new Map()){
      if(cache.get(target)){
          return cache.get(target)
      }
      if(target instanceof Object){
          let dist ;
          if(target instanceof Array){
            // 拷贝数组
            dist = [];
          }else if(target instanceof Function){
            // 拷贝函数
            dist = function () {
              return target.call(this, ...arguments);
            };
          }else if(target instanceof RegExp){
            // 拷贝正则表达式
           dist = new RegExp(target.source,target.flags);
          }else if(target instanceof Date){
              dist = new Date(target);
          }else{
            // 拷贝普通对象
            dist = {};
          }
          // 将属性和拷贝后的值作为一个map
          cache.set(target, dist);
          for(let key in target){
              // 过滤掉原型身上的属性
            if (target.hasOwnProperty(key)) {
                dist[key] = deepClone(target[key], cache);
            }
          }
          return dist;
      }else{
          return target;
      }
    }

    https://juejin.im/post/6889327058158092302

    差集

    var arr1 = [{id:1},{id:2}, {id:4}, {id:9}, {id:0}];
    var arr2 = [2,0, 4];
    var difference = function(arr1, arr2) {
           var diff = [];
           var tmp = arr2;
           $(arr1).each(function(i,val1){
                 if (arr2.indexOf(val1.id) < 0) {
                       diff.push(val1);
                 }
           });
           console.log(diff);
         }
    difference(arr1, arr2);
  • 相关阅读:
    centos6:一个网卡上显示多个ip地址的错误
    博客搬家到CSDN:http://blog.csdn.net/yeweiouyang
    Codeforces Round #430 (Div. 2)
    Codeforces Round #430 (Div. 2)
    Codeforces Round #430 (Div. 2)
    Codeforces Round #426 (Div. 2)
    Codeforces Round #427 (Div. 2)
    Codeforces Round #427 (Div. 2)
    Codeforces Round #427 (Div. 2)
    Codeforces Round #427 (Div. 2)
  • 原文地址:https://www.cnblogs.com/liufeiran/p/13903482.html
Copyright © 2011-2022 走看看