0
0

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.

三項演算子を使って、数値の往復処理をちょっと綺麗に書く

Last updated at Posted at 2019-10-23

まえがき

ある数値が下限に達したら増え、上限に達したら減るという処理を綺麗に書けたらいいなという記事です。
軽い内容なので休憩程度に読んでいただけたらと思います。

コード

let targetNum = 0
let status = 0
const max = 100
const min = -100

status === 0
  ? targetNum !== max
    ? targetNum++
    : status = 1
  : targetNum !== min
    ? targetNum--
    : status = 0

//if文で書いた場合こうなる
if (status === 0) {
  if (targetNum !== max) {
    targetNum++
  } else {
    status = 1
  }
} else {
  if (targetNum !== min) {
    targetNum-- 
  } else {
    status = 0
  }
}

説明

見ての通り、「targetNumが、max・minに達していなければ増減させ、達していればstatusを切り替える」というシンプルな処理を、三項演算子のネストを用いて書いています。(蛇足ですが個人的には、ネスト1階層までなら実用的かなと考えています)

今回はわかりやすく整数を使い、上限値、下限値を超える想定もしていないコードですが、条件式の部分をいじれば色々応用は効くかと思います。

それでは!

0
0
2

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?