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.

+で型を数値型に無理やり変換してisNaNで制御

Last updated at Posted at 2021-10-23

変数の前に+を書くことで数字になる

const number123 = 123;
typeof(number123); // number
const string123 = "123";
typeof(string123); // string
const hoge = "hoge"
typeof(hoge); // string

変数の前に+を書くことで、string123は数値(123)になり、hogeNaNになる。

const changeString123 = +string123;
typeof(changeString123); // number
console.log(changeString123); // 123

const changeHoge = +hoge
typeof(changeHoge); // number
console.log(changeHoge); // NaN

数字か文字列かはisNaN()で判断

isNaN(changeString123); // isNaN(123)⇒false
isNaN(changeHoge); // isNaN(NaN)⇒true

余談・こんな時に使いました

Next.jsにて、現在いるパスが年(2021とか)の数字である定義。それ以外はエラーページを出す。

import { useRouter } from 'next/router';

const router = useRouter();
const thisSlug = router.query.year;
/* /[year]/[month]/[day]を想定 */

yearもといthisSlugが数値であってほしい設計。hugafooなど受け取っても、ページとしての整合性が取れなくなる。

よって、上記のやり方を適用した。

const router = useRouter();
const thisSlug = +router.query.year;
if (isNaN(thisSlug)){
  return (
    <>
      <p>illegal use of url...</p>
    </>
  )
}
0
0
1

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?