JS 객체 복제(심층 및 얕은 복제)

1. 얕은 복사


1、Object.assign(target,source,source...)


a, 여러 객체 복제 지원
b. 소스와 target 속성이 같으면 소스는 target의 속성을 복사합니다
c, target은 Object 객체로만 사용 가능

var obj = {a:1,b:2}
undefined
Object.assign({c:3},obj)
{c: 3, a: 1, b: 2}
obj
{a: 1, b: 2} 
 if(Object.assign){// }else{// }

2, 확장 연산자(spread)


여러 객체를 하나의 객체로 복사 지원"

var obj1 = { foo: "foo" };
var obj2 = { bar: "bar" };
 
var copySpread = { ...obj1, ...obj2 }; // Object {foo: "foo", bar: "bar"}
copySpread 
{foo: "foo", bar: "bar"}
var obj = {a:1,b:2,c:3}
var objs = {...obj}
objs
{a: 1, b: 2, c: 3}
objs.a=10
10
objs
{a: 10, b: 2, c: 3}
obj
{a: 1, b: 2, c: 3}

2. 딥 카피


1. JSON을 정렬하기 위해 객체를 사용합니다.stringify () 및 JSON.parse()


참고: 이 메서드는 원래 객체에 정렬할 수 있는 값 유형이 있고 순환 참조가 없는 경우에만 유효합니다.정렬할 수 없는 값 유형의 한 예는 Date 객체 - JSON입니다.parse는 문자열로만 해석할 수 있고 원래 Date 대상이나 대상의 속성 값은function으로 해석할 수 없습니다

var obj = {a:1,b:[1,2,3],c:{e:3},bool:false}
undefined
var objs = JSON.parse(JSON.stringify(obj))
undefined
objs
{a: 1, b: Array(3), c: {…}, bool: false}
objs.bool = true
true
objs
{a: 1, b: Array(3), c: {…}, bool: true}
obj
{a: 1, b: Array(3), c: {…}, bool: false}

2. 귀속을 사용하여 대상의 속성을 판단한다


function deepClone(obj) {
  var copy;
 
  //   obj   null、undefined    ,  obj
  // Handle the 3 simple types, and null or undefined
  if (null == obj || "object" != typeof obj) return obj;
 
  // Handle Date
  if (obj instanceof Date) {
    copy = new Date();
    copy.setTime(obj.getTime());
    return copy;
  }
 
  // Handle Array
  if (obj instanceof Array) {
    copy = [];
    for (var i = 0, len = obj.length; i < len; i++) {
        copy[i] = clone(obj[i]);
    }
    return copy;
  }
 
  // Handle Function
  if (obj instanceof Function) {
    copy = function() {
      return obj.apply(this, arguments);
    }
    return copy;
  }
 
  // Handle Object
  if (obj instanceof Object) {
      copy = {};
      for (var attr in obj) {
          if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
      }
      return copy;
  }
 
  throw new Error("Unable to copy obj as type isn't supported " + obj.constructor.name);
}
다음은 JS 개체 복제(심층 복사 및 얕은 복사)에 대한 상세한 내용입니다. JS에 대한 더 많은 자료는 저희의 다른 관련 글에 주목하십시오!

좋은 웹페이지 즐겨찾기