47
43

More than 3 years have passed since last update.

JavaScriptでArrayに対する破壊的メソッドを安全に使う方法

Last updated at Posted at 2020-04-06

これは何

@Shokorep さんにより、JSの破壊・非破壊メソッドがまとまっている記事が書かれていましたが、私のこの記事では「破壊的な関数をどうやって安全に使うか」という話を書こうと思います。

破壊的とは

対象となるArrayの中身を変えてしまうこと。
例えば reverse() ですと以下のようになります。

image.png

元のArrayであるarr1の中身が変わってしまっています。

破壊的なものを安全に使う

一回配列展開をしてあげると元のArrayとは無関係になるので、安全に使用することができます。

スプレッド構文([...arr])を使う方法

image.png

concat() を使う方法

image.png

47
43
7

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
47
43