Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

30
31

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.

JavaScriptで配列の要素を入れ替える方法

Last updated at Posted at 2022-04-22

はじめに

表題の件ですが、分割代入を使うと簡単です。

分割代入 (Destructuring assignment) 構文は、配列から値を取り出して、あるいはオブジェクトからプロパティを取り出して別個の変数に代入することを可能にする JavaScript の式です。

処理

let hoge = [1, 2, 3, 4];
console.log(hoge);

[hoge[0], hoge[1]] = [hoge[1], hoge[0]];
console.log(hoge);

実行結果

[1, 2, 3, 4]
[2, 1, 3, 4]

ちなみに文字列でも問題なく可能です。

let hoge = ["a", "b", "c", "d"];
console.log(hoge);

[hoge[0], hoge[1]] = [hoge[1], hoge[0]];
console.log(hoge);

実行結果

['a', 'b', 'c', 'd']
['b', 'a', 'c', 'd']

参考

30
31
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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
30
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?