LoginSignup
2
0

More than 3 years have passed since last update.

【JavaScript】配列/オブジェクトの色々な値渡し

Last updated at Posted at 2020-12-22

書くきっかけ

値渡しのやり方が色々あったのでまとめておこうと思いました。
配列やオブジェクトが入れ子になっていると書き方も変わります。(ここで結構ハマりました)

基本の参照渡し

配列やオブジェクトのコピーは基本的に参照渡しとなります。

const xx = [0,1,2]
const yy = xx
yy[0] = 9    // xx[0]を変えているも同じ。
console.log(xx)    // [9,1,2]

const aa = { x:0, y:0 }
const bb = aa
bb.x = 1    // aa.xを変えているも同じ。
console.log(aa)    // { x:1, y:0 }

値渡し

単純に値だけのコピーをしたい時があります。
やり方を以下にまとめます。

配列の値コピー

const xx = [0,1,2]

const yy1 = xx.slice()      //値コピー
const yy2 = Array.from(xx)  //値コピー
const yy3 = xx.map(v => v)  //値コピー
const yy4 = xx.concat()     //値コピー
const yy5 = [...xx]         //値コピー

配列の値コピー(入れ子)

const xxNested = [{ x:0, y:0 }]

const yyNested = JSON.parse(JSON.stringify(xxNested))  //値コピー

オブジェクトの値コピー

const aa = { x:0, y:0 }

const bb1 = Object.assign({}, aa)  //値コピー
const bb2 = {...aa}                //値コピー

オブジェクトの値コピー(入れ子)

const aaNested = { x:[0,1,2] }

const bbNested = JSON.parse(JSON.stringify(aaNested))  //値コピー

こちらからは以上です。

参考

2
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
2
0