LoginSignup
1
0

More than 3 years have passed since last update.

Javascriptの配列とObjectのコピー関連メモ

Last updated at Posted at 2021-03-08

自分用のメモ

Array

ポインタ有りの場合

const arr1 = ['a', 'b', 'c', 'd'];
const arr2 = arr1;
arr2[0] = 'e';

console.log(arr1); //- ['e', 'b', 'c', 'd']
console.log(arr2); //- ['e', 'b', 'c', 'd']
//- arr1[0]も同じ値になる

ポインタ無しの場合

const arr1 = ['a', 'b', 'c', 'd'];
const arr2 = arr1.slice();
arr2[0] = 'e';

console.log(arr1); //- ['a', 'b', 'c', 'd']
console.log(arr2); //- ['e', 'b', 'c', 'd']
//- arr1[0]とは同じ値にならない

Object

ポインタ有りの場合

const obj1 = {
  data1: 'a',
  data2: 'b',
  data3: 'c',
  data4: 'd'
};
const obj2 = obj1;
obj2.data1 = 'e';

console.log(obj1); 
/*
{
  data1: 'e',
  data2: 'b',
  data3: 'c',
  data4: 'd'
}
*/
console.log(obj2); 
/*
{
  data1: 'e',
  data2: 'b',
  data3: 'c',
  data4: 'd'
}
*/
//- obj1.data1も同じ値になる

ポインタ無しの場合

const obj1 = {
  data1: 'a',
  data2: 'b',
  data3: 'c',
  data4: 'd'
};
const obj2 = Object.assign({}, obj1);
obj2.data1 = 'e';

console.log(obj1); 
/*
{
  data1: 'a',
  data2: 'b',
  data3: 'c',
  data4: 'd'
}
*/
console.log(obj2); 
/*
{
  data1: 'e',
  data2: 'b',
  data3: 'c',
  data4: 'd'
}
*/
//- obj1.data1とは同じ値にならない
1
0
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
1
0