10
2

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 1 year has passed since last update.

ElixirAdvent Calendar 2022

Day 15

Elixirから覚えるJavaScript 〜sort(変数の挙動)〜

Last updated at Posted at 2023-01-02

僕は普段はElixirを使ってます
必要になったのでJavaScriptの勉強をはじめました
題名はElixirから覚えるJavaScriptですが、逆もできるかも?

今回はsortについて挙動を確認したいと思います
別にsortでなくてもよい、変数がどのように管理されているか知りたかった

Elixir

arr = [5, 4, 3, 2, 1]
x = arr |> Enum.sort()
IO.inspect(arr)
IO.inspect(x)
実行結果
[5, 4, 3, 2, 1]
[1, 2, 3, 4, 5]

JavaScript

arr = [5, 4, 3, 2, 1];
x = arr.sort();
console.log(arr);
console.log(x);
実行結果
[ 1, 2, 3, 4, 5 ]
[ 1, 2, 3, 4, 5 ]

arrが書き換わってしまう…

と言うことで対策
スプレッド構文...を使ってみる

arr = [5, 4, 3, 2, 1];
x = [...arr].sort();
console.log(arr);
console.log(x);
実行結果
[ 5, 4, 3, 2, 1 ]
[ 1, 2, 3, 4, 5 ]

無事に同じ結果になりました

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?