美文网首页
2018-05-22

2018-05-22

作者: 相信自己_胡 | 来源:发表于2018-05-22 10:00 被阅读0次

    数组与对象的深拷贝

    对象
    //1
    var newObject = JSON.parse(JSON.stringify(oldObject));
    
    //2
    function clone(obj) {
          if (obj === null || typeof(obj) !== 'object' || 'isActiveClone' in obj)
            return obj;
    
          if (obj instanceof Date)
            var temp = new obj.constructor(); //or new Date(obj);
          else
            var temp = obj.constructor();
    
          for (var key in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, key)) {
              obj['isActiveClone'] = null;
              temp[key] = clone(obj[key]);
              delete obj['isActiveClone'];
            }
          }
    
          return temp;
        }
    
    // Shallow copy
    var newObject = jQuery.extend({}, oldObject);
    
    // Deep copy
    var newObject = jQuery.extend(true, {}, oldObject);
    
    数组
    let a=[1,2,3]
    let b=a.slice();
    let c=a.concat();//或者使用ES7  let c = [...a],转码后也是concat
    console.log(a === b)//false
    console.log(a === c)//false
    

    相关文章

      网友评论

          本文标题:2018-05-22

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