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

【JavaScript】数値範囲による分岐

Last updated at Posted at 2020-08-08

#前置き

ふと、数値の範囲で分岐させるのって面倒だったなぁと思い返したはいいけど、どう書いていたがすぐ思い出せなかったので自分用に記載。

コードはよくありそうな年代別の分岐。

#コード

const getGeneration = age => {
	if (!Number.isFinite(age)) return console.error('数値以外が入力');
	if (age<0) return console.error('0歳未満?');
	if (age<12) return console.log('12歳未満');
	if (age<20) return console.log('12歳~19歳');
	if (age<30) return console.log('20歳代');
	if (age<40) return console.log('30歳代');
	if (age<50) return console.log('40歳代');
	if (age<60) return console.log('50歳代');
	if (age<70) return console.log('60歳代');
	if (age<80) return console.log('70歳代');
	if (age<100) return console.log('80歳以上');
	if (age<120) return console.log('100歳以上');
	return console.log('120歳以上');
};

getGeneration(-1);		// => 0歳未満?
getGeneration('14');	// => 数値以外が入力
getGeneration(14);		// => 12歳~19歳
getGeneration(200);		// => 120歳以上

Number.isFinite()の行は、数値以外の入力が絶対にない状態なら削除OK。

#最後に

もっとスマートな書き方はないものか…

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