#オブジェクトや配列の複製#
オブジェクトや配列を複製しようとすると参照渡しなので元から変わってしまう。
javascript
var originalObj = { a: 1 };
var copyObj = originalObj;
copyObj.a = 100;
console.log(originalObj.a); //100
console.log(copyObj.a); //100
##オブジェクトのコピー##
従来
javascript
var originalObj = { a: 1 };
var copyObj = {};
for (var key in originalObj) {
copyObj[key] = originalObj[key];
}
copyObj.a = 100;
console.log(originalObj.a); //1
console.log(copyObj.a); //100
ES6
es6
let originalObj = { a: 1 };
let copyObj = {};
Object.assign(copyObj , originalObj);
copyObj.a = 100;
console.log(originalObj.a); //1
console.log(copyObj.a); //100
##配列のコピー##
従来
javascript
var originalArr = [1, 2, 3];
var copyArr = [];
for (var i = 0, len = originalArr.length; i < len; i++) {
copyArr.push(originalArr[i]);
}
copyArr[0] = 100;
console.log(originalArr); //[1, 2, 3]
console.log(copyArr); //[100, 2, 3]
ES6
es6
let originalArr = [1, 2, 3];
let copyArr = [];
Object.assign(copyArr , originalArr);
copyArr[0] = 100;
console.log(originalArr); //[1, 2, 3]
console.log(copyArr); //[100, 2, 3]
##注意##
1階層のオブジェクトや配列の複製は簡単になったけど2階層目にオブジェクトや配列がある場合参照になってしまう…
es6
let originalObj = {
a: 1,
b: [1, 2]
};
let copyObj = {};
Object.assign(copyObj , originalObj);
copyObj.a = 100;
copyObj.b[0] = 100;
console.log(originalObj.a, originalObj.b); //1, [100, 2] 変わる
console.log(copyObj.a, copyObj.b); //100, [100, 2]