JSは浅いコピーと深いコピーです.

1431 ワード

1.レプリカ(引用タイプのコピーは全部レプリカ)
var arr1 = [1,2,3,4];
arr2 = arr1;
arr2.push(5);
console.log(arr1);//[1,2,3,4,5]
2.対象の浅いコピー
function copy(obj){
  var tempObj = {};
  for(var i in obj){
    tempObj[i] = obj[i]; //    
  }
  return tempObj
}
var Person = {
  name:'person',
  skills:['g','s','m']
}
var newPerson = copy(Person);
console.log(Person.skills ) ;//['g','s','m'];
newPerson.skills.push('b');
console.log(Person.skills); // ['g','s','m','b'];    ,              
console.log(newPerson .skills); // ['g','s','m','b']; 
2.対象の深度コピー(浅いコピーをもとに再帰的に呼び出し)
function deepCopy(obj, newObj) {
  var tempObj= newObj || {};
  for (var i in obj) {
    if (typeof obj[i] === 'object') {
      tempObj[i] = (obj[i].constructor === Array) ? [] : {};
      deepCopy(obj[i], tempObj[i]);
    } else {
      tempObj[i] = obj[i];
    }
  }
  return tempObj;
};
var Person = {
  name:'person',
  skills:['g','s','m']
}
var newPerson = deepCopy(Person);
console.log(Person.skills ) ;//['g','s','m'];
newPerson.skills.push('b');
console.log(Person.skills); // ['g','s','m']; 
console.log(newPerson .skills); // ['g','s','m','b'];