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 1 year has passed since last update.

Numberオブジェクトって結構厄介

Posted at

Numberオブジェクトの挙動が意外にも厄介だったのでまとめておく。

something.js
Number("0"); // → 0 
Number("hoge"); // → NaN
Number(""); // → 0 (NaNじゃないんかい)

Reactにおいて、以下のようにクエリの値に応じて表示する内容を変えようと思ったのだが、実際にはクエリが指定されていない場合、blockID=0となってしまうため、「0以上やで〜」が表示されてしまう。

something.tsx
// 省略

const component = () => {
    // urlは、https://localhost:3000/something
    const location = useLocation();
    const search = location.search;
    const query = new URLSearchParams(search);
    const blockID = Number(query.get("id"));

    return(<>
        {/* 「クエリないで〜」が表示されるようにしたい */}
        {Number.isNaN(blockID) && <div>クエリないで〜</div>}
        {blockID >= 0 && <div>0以上やで〜</div>}
    </>);
}
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?