Skip to content

Instantly share code, notes, and snippets.

@think49
Created March 9, 2011 12:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save think49/862085 to your computer and use it in GitHub Desktop.
Save think49/862085 to your computer and use it in GitHub Desktop.
get-type.js : ECMAScript5 準拠のデータ型を返す
/**
* get-type.js
*
* @version 1.0.2
* @author think49
* @url https://gist.github.com/862085
* @license http://www.opensource.org/licenses/mit-license.php (The MIT License)
*/
function getType (value) {
var type, typeofValue;
if (value === null) { // Null Type
return 'Null';
}
typeofValue = typeof value;
switch (typeofValue) {
case 'undefined': // Undefined Type
case 'boolean': // Boolean Type
case 'number': // Number Type
case 'string': // String Type
type = typeofValue.charAt(0).toUpperCase() + typeofValue.slice(1);
break;
case 'object': // Object Type (native and does not implement [[Call]])
case 'function': // Object Type (native or host and does implement [[Call]])
default: // Object Type (host and does not implement [[Call]])
type = 'Object';
break;
}
return type;
}
@think49
Copy link
Author

think49 commented Mar 29, 2011

get-type.js

使い方

第一引数で渡した値の を返します。

alert(getType(undefined));     // "Undefined"
alert(getType(true));          // "Boolean"
alert(getType(1));             // "Number"
alert(getType("sample"));      // "String"
alert(getType({}));            // "Object"
alert(getType([]));            // "Object"
alert(getType(function(){}));  // "Object"
alert(getType(new Boolean())); // "Object"
alert(getType(new Number()));  // "Object"
alert(getType(new String()));  // "Object"
alert(getType(new Object()));  // "Object"
alert(getType(new Array()));   // "Object"

Object 型だけを判定したいなら

typeof 演算子で判定が面倒なのは Object 型だけなので、Object 型以外の判定は独自の関数を使う必要がないかもしれません。
is-object.js を使えば、対象が Object 型かどうか判定できます。

参考リンク

ECMAScript 3

ECMAScript 5.1

その他

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment