javascript 型を取得する

javascript 型を取得する

javascriptで、型を取得するサンプルコードを記述してます。「typeof」を使用すると値から型を取得することができます。

環境

  • OS windows11 home
  • Apache 2.4.43
  • ブラウザ chrome 107.0.5304.88

型を取得

型を取得する場合は「typeof」を使用します。

typeof 値

実際に、複数の値から型を取得してみます。

console.log( typeof 10 );
// 結果 number

console.log( typeof 1.11 );
// 結果 number

console.log( typeof 0 );
// 結果 number

console.log( typeof Number.MAX_VALUE );
// 結果 number

console.log( typeof Number.MIN_VALUE );
// 結果 number

console.log( typeof NaN );
// 結果 number

console.log( typeof Infinity );
// 結果 number

console.log( typeof 10n );
// 結果 bigint

console.log( typeof 'abc' );
// 結果 0

console.log( typeof true );
// 結果 boolean

console.log( typeof false );
// 結果 boolean

console.log( typeof '' );
// 結果 string

console.log( typeof `` );
// 結果 string

console.log( typeof '<p>' );
// 結果 string

console.log( typeof null );
// 結果 object

console.log( typeof [1] );
// 結果 object

console.log( typeof {a:'abc'} );
// 結果 object

console.log( typeof new String() );
// 結果 object

console.log( typeof document.body );
// 結果 object

console.log( typeof void 0 );
// 結果 undefined

console.log( typeof undefined );
// 結果 undefined

console.log( typeof Symbol() );
// 結果 symbol

型を判定する場合は、以下のように条件式を使用します。

let num = 1;

if (typeof num === 'number'){
  console.log('数値');
}

また、「typeof」を使用せずに型判定を行うこともできます。

サンプルコード

以下は、
「実行」ボタンをクリックして、フォームに入力された値がstring型であるかを判定した結果を表示するサンプルコードとなります。

※cssには「tailwind」を使用して、アロー関数で関数は定義してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
</head>

<script>

  const hoge = () => {

    (typeof txt.value === 'string') ? foo.textContent = '文字列' : foo.textContent = '文字列以外'

  }

  window.onload = () => {

    btn.onclick = () => { hoge() }

  }

</script>

<body>
  <div class="container mx-auto my-56 w-64 px-4">

    <div id="sample" class="flex flex-col justify-center">

      <h1 class="font-semibold text-neutral-500 text-lg mr-auto">実行結果</h1>

      <p id="foo" class="font-semibold text-lg mr-auto"></p>

      <input
      class="mt-5 bg-gray-200 appearance-none border-2 border-gray-200 rounded w-full py-2 px-4 text-gray-700 leading-tight focus:outline-none focus:bg-white focus:border-gray-500"
      id="txt" type="text">

      <button id="btn"
        class="mb-2 md:mb-0 bg-transparent hover:bg-lime-500 text-lime-700 font-semibold hover:text-white py-2 px-4 border border-lime-500 hover:border-transparent rounded">
        実行
      </button>

    </div>

  </div>
</body>

</html>

実行結果を確認すると、テキストフォームから入力された値は全て「String型」になることが確認できます。