2011-07-05 6 views
1
JavaScriptで

、どのように私は言ってやる:Javascriptを1.6に変数のタイプをチェックするためのショートカット構文はありますか?

switch (typeof obj) { 
    case 'number': 
    case 'boolean': 
    case 'undefined': 
    case 'string': 
    // You get here for any of the four types 
    break; 
} 

:あなたはswitchを使用することができます

if (typeof obj in('number','boolean','undefined','string')) { 
+0

最初の声明で改善したいですか? –

+0

ちょうど好奇心が強い - なぜあなたは非常に多くのタイプをチェックする必要がありますか?私は以前これを行う必要はなかった。 –

答えて

2

もっとグリスト:

if (('object function string undefined').indexOf(typeof x) > -1) { 
    // x is an object, function, string or undefined 
} 

または

if ((typeof x).match(/object|function|string|undefined/)) { 
    // x is an object, function, string or undefined 
} 

あなたはこの猫は皮たいどのように多くの方法?

+0

これらは、4つのタイプ名のいずれかの部分文字列であったすべてのタイプにも一致します。 – Guffa

6

つまり
if (typeof obj === 'number' 
    || typeof obj === 'boolean' 
    || typeof obj === 'undefined' 
    || typeof obj === 'string') { 

、のいくつかの種類があります:

if (['number','boolean','undefined','string'].indexOf(typeof obj) !== -1) { 
    // You get here for any of the four types 
} 
+0

スイッチのステートメントには常にデフォルトのブロックが必要です。 – RobG

+0

@RobG:コードがないのに? – Guffa

+0

はい、ただのコンベンションで、他の言語との一貫性があり、すべてのケースが失敗した場合にどうなるかを明確にするでしょう。 – RobG

4

あなたははい、あり

var acceptableTypes = {'boolean':true,'string':true,'undefined':true,'number':true}; 

if (acceptableTypes[typeof obj]){ 
    // whatever 
} 

以上の冗長

if (typeof obj in acceptableTypes){ 
    // whatever 
} 
3

ようなもので、それを近似することができます。 typeof(obj)は単なる文字列を返すので、文字列は、文字列の任意のセット内にある場合は、チェックする場合と同様に、あなたは簡単に行うことができます。

if (typeof(obj) in {'number':'', 'boolean':'', 'undefined':'', 'string':''}) 
{ 
    ... 
} 

またはあなたはそれをさらに短くすることができます。 typeofが返す「タイプ」は、number,stringbooleanobjectfunctionundefinedなので、代わりに除外することができます。

if (!(typeof(obj) in {'function':'', 'object':''})) 
{ 
    ... 
} 
+0

* typeof *は演算子であるため、グループ化演算子は不要です。したがって、 'typeof obj'は十分であり、より好ましいものです。 – RobG

1

私は、同様の状況で関数型プログラミングを使用するのが好きです。 だから、それをより読みやすくするために、underscore.jsを使用することができます:ミル用

_.any(['number','boolean','undefined','string'], function(t) { 
    return typeof(obj) === t; 
}); 
関連する問題