5
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.

Elixirから覚えるJavaScript 〜Arrayで追加と取出し〜

Last updated at Posted at 2023-01-05

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

今日はJavaScriptではArrayで追加と取出しを見てみたいと思います
※ElixirはList

お題
a)、[1, 2, 3, 4, 5]に値を追加して[1, 2, 3, 4, 6]にする、そして元の変数の影響を調査
b)、[1, 2, 3, 4, 5]を先頭の要素1と後ろの要素[2, 3, 4, 5]に分割する

a)、[1, 2, 3, 4, 5]に値を追加して[1, 2, 3, 4, 6]にする、そして元の変数の影響を調査

Elixir

x = [1, 2, 3, 4, 5]
y = x ++ [6]       
IO.inspect(x)
IO.inspect(y)
実行結果
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]

JavaScript

x = [1, 2, 3, 4, 5]
y = x.push(6)
実行結果
[ 1, 2, 3, 4, 5, 6 ]
6

想像していた動きと違ったのでElixirと同じ結果を求めたい

x = [1, 2, 3, 4, 5]
y = [...x]
y.push(6)
console.log(x)
console.log(y)
実行結果
[ 1, 2, 3, 4, 5 ]
[ 1, 2, 3, 4, 5, 6 ]

JavaScript別の方法(こっちのほうが求めている答え)

@mnishiguchiさんに教えてもらいました
ありがとうございます

x = [1, 2, 3, 4, 5]
y = x.concat(6)
console.log(x)
console.log(y)
実行結果
[ 1, 2, 3, 4, 5 ]
[ 1, 2, 3, 4, 5, 6 ]

b)、[1, 2, 3, 4, 5]を先頭の要素1とに後ろの要素[2, 3, 4, 5]に分割する

Elixir

x = [1, 2, 3, 4, 5]
[h | t] = x        
IO.inspect(x)
IO.inspect(h)
IO.inspect(t)
実行結果
[1, 2, 3, 4, 5]
1
[2, 3, 4, 5]

JavaScript

x = [1, 2, 3, 4, 5]
[h, ...t] = [1, 2, 3, 4, 5]
console.log(x)
console.log(h)
console.log(t)
実行結果
[ 1, 2, 3, 4, 5 ]
1
[ 2, 3, 4, 5 ]

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

5
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
5
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?