基本的に、次の2つを区別する必要があります。
var simple = 5 // or "word", or 56.78, or any other "simple" object
var complex = {propname: "propvalue", "otherprop": "othervalue"}
基本的に、次の2つを区別する必要があります。
var simple = 5 // or "word", or 56.78, or any other "simple" object
var complex = {propname: "propvalue", "otherprop": "othervalue"}
演算子を使用typeof
すると、次のことを判断できます。
"number" Operand is a number
"string" Operand is a string
"boolean" Operand is a Boolean
"object" Operand is an object
"undefined" Operand is not defined.
編集:typeof null
コメントで提案されているように、オブジェクトを返すよう
に、値が null かどうかも確認する必要があります。
使用できますtypeof
:
typeof 5 == "number";
typeof 1.5 == "number";
typeof true == "boolean";
typeof "word" == "string";
typeof {} == "object";
基本的:
if(obj == null) {
//null or undefined
}
else if(typeof obj == "object") {
//It's "complex"
}
else {
//Primitive or "simple"
}
注:null
が返さ"object"
れるため、確認する必要があります。
問題は、{}だけではなく「オブジェクト」のタイプを返すことです。
typeof 5 == 'number'
typeof NaN == 'number'
typeof 'test' == 'string'
typeof true == 'boolean'
typeof undefined == 'undefined'
typeof null == 'object'
typeof /asdf/ == 'object' // this is true in some engines, like Firefox's. Not in V8 (in which it is 'function')
typeof [] == 'object'
typeof {} == 'object'
ただし、toStringを使用すると、さらに確認できます。
toString.call(null) == '[object Window]' // or '[object global]' or '[object Null]' - depends on engine
toString.call(/asdf/) == '[object RegExp]'
toString.call([]) == '[object Array]'
toString.call({}) == '[object Object]'
したがって、確認する最良の方法は次のとおりです。
var test;
test = {};
typeof test == 'object' && toString.call(test) == '[object Object]'; // true
test = [];
typeof test == 'object' && toString.call(test) == '[object Object]'; // false
// et cetera
お役に立てば幸い
Object.prototype.getName = function() {
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec((this).constructor.toString());
return (results && results.length > 1) ? results[1] : "";
};
var simple = 5; // or "word", or 56.78, or any other "simple" object
var complex = { propname : "propvalue"
, "otherprop" : "othervalue"
};
simple.getName(); // returns: "Number"
complex.getName(); // returns: "Object"
以下を試してください
if (typeof obj === 'object') {
// It's complex
} else {
// It's not
}
単純な型に対して true を返す単純な関数を作成できます。
function isSimple( a ) {
return (typeof a).match(/(number)|(boolean)|(string)/)
}
これはNaN
、数値と見なされる場合は true を返し、「未定義」の場合は false を返しますが、特定のケースに合わせてこれを簡単に変更できます。
以下のスニペットを実行して、動作を確認してください
<script>
// return true/false if typeof matches simple regex pattern
function isSimple( a ) {
return (typeof a).match(/(number)|(boolean)|(string)/);
}
// setup some tests cases
var tests = [
[1,2,3],
'hello',
7,
{ foo: 'bar' },
NaN
]
// log output of isSimple function against each test case
for( var i in tests ) {
var value = tests[ i ];
if( isSimple( value ) ) {
console.log( 'simple value', value );
} else {
console.log( 'not simple', value );
}
}
</script>