0
1

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 3 years have passed since last update.

javascriptのスプレッド構文

Last updated at Posted at 2021-07-27

##スプレッド構文とは

配列を展開したり、まとめたりすることができる構文

#####配列を展開する

const array = [1, 2]

console.log(array); // [1, 2]
//スプレッド構文
console.log(...array); // 1, 2

//↑は↓と同じことを行っている
console.log(array[0], array); // 1, 2

#####分割代入の際に配列を部分的にまとめる

const array2 = [1, 2, 3, 4, 5];
const [num1, num2, ...array3] = array2
console.log(num1); // 1
console.log(num2); // 2
console.log(...array3); // [3, 4, 5]

#####配列のコピーや結合

const array4 = [10, 20];
const array5 = [30, 40];

const array6 = [...array4];
console.log(array6); //[10, 20]
array6[0] = 100; //配列の中身を変更
console.log(array6); //[100, 20] 変わってる!
console.log(array4); //[10, 20] 参照先の配列は変わっていない!

const array7 = [...array4, ...array5];
console.log(array7); //[10, 20, 30, 40]

スプレットじゃなくてそのまま代入すればいいじゃん!

const array8 = array4;
console.log(array8); //[10, 20]

確かに代入されてる!けど...

const array4 = [10, 20];

const array8 = array4;
array8[0] = 100;
console.log(array8); //[100, 20] 変わってる!
console.log(array4); //[100, 20] 参照先の中身まで変わってる!

中身を変更すると、参照先の配列の中身も変わっている!!(参照わたし)
だから、配列のコピーや結合を行う際はスプレッド構文を使用する

0
1
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?