Java では、変数に対してinstanceOf
または を使用してその型を調べることができます。getClass()
厳密に型指定されていない JavaScript の変数の型を調べるにはどうすればよいでしょうか?
たとえば、 がbar
なのか、Boolean
なのかNumber
、 なのかをどうやって確認すればよいでしょうかString
?
function foo(bar) {
// what do I do here?
}
ベストアンサー1
使用typeof
:
> typeof "foo"
"string"
> typeof true
"boolean"
> typeof 42
"number"
つまり、次のことができます:
if(typeof bar === 'number') {
//whatever
}
ただし、これらのプリミティブをオブジェクト ラッパーで定義する場合は注意してください (これは絶対に行わないでください。可能な場合は常にリテラルを使用してください)。
> typeof new Boolean(false)
"object"
> typeof new String("foo")
"object"
> typeof new Number(42)
"object"
配列の型は依然として ですobject
。ここで本当に必要なのはinstanceof
オペレーター。
アップデート:
もう一つの興味深い方法は、Object.prototype.toString
:
> Object.prototype.toString.call([1,2,3])
"[object Array]"
> Object.prototype.toString.call("foo bar")
"[object String]"
> Object.prototype.toString.call(45)
"[object Number]"
> Object.prototype.toString.call(false)
"[object Boolean]"
> Object.prototype.toString.call(new String("foo bar"))
"[object String]"
> Object.prototype.toString.call(null)
"[object Null]"
> Object.prototype.toString.call(/123/)
"[object RegExp]"
> Object.prototype.toString.call(undefined)
"[object Undefined]"
これにより、プリミティブ値とオブジェクトを区別する必要がなくなります。