JavaScript

typeof演算子

 編集:2022.08.07 by T.A.

未評価のオペランドの型を示す文字列を返します。

typeof operand
typeof(operand)
operand オブジェクトまたは型を表す式。

以下は typeof が返す事が出来る値(文字列)の一覧表です。型と の詳細については、 のページも参照してください。

返り値
Undefined "undefined"
Null "object"(下記参照)
真偽値 "boolean"
数値 "number"
BigInt(ECMAScript 2020 の新機能) "bigint"
文字列 "string"
シンボル(ECMAScript 2015 の新機能) "symbol"
Function オブジェクト(implements [[Call]] in ECMA-262 terms) "function"
その他のオブジェクト "object"

数値:

D=typeof 37	//=number
D=typeof 3.14	//=number
D=typeof(42)	//=number
D=typeof Math.LN2	//=number
D=typeof Infinity	//=number
D=typeof NaN	//=number
D=typeof Number('1')	//=number
D=typeof Number('shoe')	//=number
D=typeof 42n	//=bigint

文字列:

D=typeof ''	//=string
D=typeof 'bla'	//=string
D=typeof `template literal`	//=string
D=typeof '1'	//=string
D=typeof (typeof 1)	//=string: typeof は常に文字列を返す。
D=typeof String(1)	//=string

真偽値:

D=typeof true	//=boolean
D=typeof false	//=boolean
D=typeof Boolean(1)	//=boolean
D=typeof !!(1)	//=boolean: 論理 NOT 演算子 2 つの呼び出しは、Boolean() と同等です。

シンボル:

D=typeof Symbol()	//=symbol
D=typeof Symbol('foo')	//=symbol
D=typeof Symbol.iterator	//=symbol

Undefined:

D=typeof undefined	//=undefined
D=typeof declaredButUndefinedVariable	//=undefined: まだ定義していない

オブジェクト:

D=typeof {a: 1}	//=object

Array.isArray または Object.prototype.toString.call を使用して、通常のオブジェクトと配列を区別します。

D=typeof [1, 2, 4]	//=object
D=typeof new Date()	//=object
D=typeof /regex/	//=object: (正規表現)

関数:

D=typeof function() {}	//=function
D=typeof class C {}	//=function
D=typeof Math.sin	//=function

以下のようなものは、紛らわしく、危険で、無駄なものです。それらの使用を避けてください。

D=typeof new Boolean(true)	//=object
D=typeof new Number(1)	//object
D=typeof new String('abc')	//=object

¶以下省く


テスト