typeof 演算子

概要

typeof 演算子はオペランドのデータ型を示す文字列を返します

演算子
実装されたバージョン JavaScript 1.1
ECMAScript エディション ECMA-262 (and ECMA-357 for E4X objects)

構文

typeof 演算子は以下の何れかの構文で使用可能です。

  1. typeof operand
  2. typeof (operand)

パラメーター

operand は、文字列、変数、キーワード、型が返されるようになっているオブジェクト。括弧は省略可能です。

説明

以下は typeof が返す事が出来る値(文字列)の一覧表です。

戻り値
未定義 "undefined"
Null "object"
真偽値 "boolean"
数値 "number"
文字列 "string"
ホストオブジェクト (provided by the JS environment) 実装に委ねる
関数オブジェクト (implements [[Call]] in ECMA-262 terms) "function"
E4X XML オブジェクト "xml"
E4X XMLList オブジェクト "xml"
他のオブジェクト "object"

通常のケース

// Numbers
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; // Despite being "Not-A-Number"
typeof Number(1) === 'number'; // but never use this form!

// Strings
typeof "" === 'string';
typeof "bla" === 'string';
typeof (typeof 1) === 'string'; // typeof always return a string
typeof String("abc") === 'string'; // but never use this form!

// Booleans
typeof true === 'boolean';
typeof false === 'boolean';
typeof Boolean(true) === 'boolean'; // but never use this form!

// Undefined
typeof undefined === 'undefined';
typeof blabla === 'undefined'; // an undefined variable

// Objects
typeof {a:1} === 'object';
typeof [1, 2, 4] === 'object'; // use Array.isArray or Object.prototype.toString.call to differentiate regular objects from arrays
typeof new Date() === 'object';

typeof new Boolean(true) === 'object' // this is confusing. Don't use!
typeof new Number(1) === 'object' // this is confusing. Don't use!
typeof new String("abc") === 'object';  // this is confusing. Don't use!

// Functions
typeof function(){} === 'function';
typeof Math.sin === 'function';

null

typeof null === 'object'; // JavaScript の誕生当初から成り立つ

JavaScript の最初の実装では、値は、型を表す「タグ」と「値そのもの」で表されていました。 オブジェクトの型タグは 0 で。そして null のそれは NULL ポインタ (0x00 は殆どのプラットフォームに存在する)で示されていました。その為 Null の型タグは 0 と見做され、「typeof Null は "object"」という、悪い冗談の様な結果になったのです。本来は Null の 型がオブジェクトである訳が無いにも関わらずです(※要出典)

この挙動は次期バージョンの ECMAScript で修正される予定(これはオプトイン経由で利用可能)であり、将来的には typeof null は 'null' を返すようになるでしょう。

正規表現

呼び出し可能な正規表現オブジェクに対して、 typeof 演算子はいくつかのブラウザで標準的でない挙動を示します (need reference to say which).

typeof /s/ === 'function'; // Chrome 1-12 ... // ECMAScript 5.1 に準拠していない
typeof /s/ === 'object'; // Firefox 5+ ...    // ECMAScript 5.1 に準拠

その他の例外的な実装

古いバージョンのInternet Explorer の alert

IE6、IE7、IE8 は以下の様な実装となっています。

typeof alert === 'object' //true

Tags (0)

タグを編集
  • No tags

Attachments (0)

 

添付ファイル