typeof とは
- ここで説明する typeof とは次の語句からなる JavaScript の演算子です。
- type
- 読み: タイプ
意味: 種類、型、形式 - of
- 読み: オブ
意味: ~の
typeof 演算子の概要
この演算子は、オペランドを評価し、その型を文字列として返します。
オペランドとは、演算の対象となる値のことで、変数 や 定数 などもこれに該当します。
構文
サンプルを見る前に構文を確認しておきます。
var strDataType = typeof operand;
var strDataType = typeof(operand);
typeof は演算子ですので記述の基本としては () は不要です。 しかし、オペランドを関数の引数のように () で括ってを記述しても問題ありません。
サンプルコードと実行結果
ここでは、変数に数種類の値を代入し、typeof でその値を評価してみます。
サンプルコード: script
<script>
let nulVariable = null;
let blnVariable = true;
let strVariable = "ywork";
let numVariable = 100;
let elmBody = document.querySelector("body");
elmBody.insertAdjacentHTML("afterbegin",
"未定義の変数 : " + typeof variable + "<br>" +
nulVariable + " : " + typeof nulVariable + "<br>" +
blnVariable + " : " + typeof blnVariable + "<br>" +
strVariable + " : " + typeof strVariable + "<br>" +
numVariable + " : " + typeof numVariable
);
</script>
- 02: nulVariable (この変数には null を代入します。)
- 03: blnVariable (この変数には true を代入します。)
- 04: strVariable (この変数には 文字列の "ywork" を代入します。)
- 05: numVariable (この変数には 数値の 100 を代入します。)
- 07-13: 結果の出力 (typeof を使って 各変数の評価を出力します。)
typeof が評価できる型と その戻り値
型 | 戻り値 |
---|---|
Undefined | "undefined" |
Null | "object" |
真偽値 | "boolean" |
数値 | "number" |
BigInt | "bigint" |
文字列 | "string" |
シンボル | "symbol" |
Function | "function" |
その他のオブジェクト | "object" |