LoginSignup
6
1

More than 5 years have passed since last update.

変数の中身を入れ替える際は分割代入を使うとスマート

Posted at
1 / 2

以下のような二つの変数があるとします。

変数を2つ用意
let a = 'A';
let b = 'B';

分割代入を使うと以下のように書くことができます。

分割代入を使った値の交換
[b, a] = [a, b];

console.log(`a の値は ${a} です。`);    // a の値は B です。
console.log(`b の値は ${b} です。`);    // b の値は A です。

ES2015が使えない環境では以下のように書きます。

古典的な値を交換するイディオム
let temp = a;

a = b;
b = temp;

以下のように一時変数を2つ用意するのは非推奨です。

冗長な値の交換
let temp1 = a;
let temp2 = b;

a = temp2;
b = temp1;
6
1
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
6
1