8
6

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 5 years have passed since last update.

【メモ】JavaScriptで変数のスワップをする

Last updated at Posted at 2019-06-02

一時変数を使わないどころかワンライナーでいける。

右辺が左から評価されて、まず200 + (b = a, 0)になり、そのあと右側が評価される。カッコの中ではまずb = aが評価され、変数bにaの値である100が入る。そして、(b = a, 0)全体の評価結果は0なので、a = 200 + 0になる。


let a = 100;
let b = 200;

a = b + (b = a, 0);

console.log({ a, b });
/*
{ a: 200, b: 100 }
*/

追記

コメントでもう一つワンライナースワップを教えていただいたので追記。


[a, b] = [b, a];
8
6
4

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
8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?