10
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

オブジェクト、配列のコピー

Posted at

#オブジェクトや配列の複製#

オブジェクトや配列を複製しようとすると参照渡しなので元から変わってしまう。

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]
10
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?