typeof演算子

広告

typeof演算子は対象となる値のデータ型を表す文字列を返す演算子です。書式は次の通りです。

typeof 値

値には数値や文字列、オブジェクトなどの値を指定します。値に応じて返される値は次の通りです。

typeof 1            = number
typeof 'Hello'      = string
typeof true         = boolean
typeof null         = object
typeof NaN          = number
typeof undefined    = undefined
typeof オブジェクト = object
typeof 配列         = object
typeof 関数         = function

演算子が返す値は文字列ですので、文字列と比較することもできます。次の例を見て下さい。

var num = 15;
if (typeof num == "number"){
  document.write("<p>変数の値は数値型です</p>");
}

変数に含まれるデータ型をtypeof演算子を使って取得しデータ型を表す文字列と比較しています。数値に対するtypeof演算子は「number」を返しますのでif文の条件式はtrueとなります。

サンプルコード

では簡単なサンプルで試してみます。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<title>JavaScript テスト</title>
</head>
<body>

<script type="text/javascript" src="./js/script15_1.js">
</script>

</body>
</html>
var person = {name:'山田', old:20};
var pref = ['東京都', '大阪府', '北海道'];
var plus = function(x, y){ return x + y; }

document.write("<p>");
document.write("typeof 1 = " + (typeof 1) + "<br />");
document.write("typeof 'Hello' = " + (typeof 'Hello') + "<br />");
document.write("typeof true = " + (typeof true) + "<br />");
document.write("typeof null = " + (typeof null) + "<br />");
document.write("typeof NaN = " + (typeof NaN) + "<br />");
document.write("typeof undefined = " + (typeof undefined) + "<br />");
document.write("typeof オブジェクト = " + (typeof person) + "<br />");
document.write("typeof 配列 = " + (typeof pref) + "<br />");
document.write("typeof 関数 = " + (typeof plus) + "<br />");
document.write("</p>");

var num = 15;
if (typeof num == "number"){
  document.write("<p>変数の値は数値型です</p>");
}

上記を実際にブラウザ見てみると次のように表示されます。

p15-1

( Written by Tatsuo Ikura )