2011-09-15 5 views
2

可能性の重複:値は文字列またはint型である場合
Finding Variable Type in JavaScript値が文字列かintかどうかをテストする方法はありますか?

どのようにしてテストすることができますか?何かのように...

X =?

XがString {}

おかげである場合、Xがint {}

ある場合!

var x = 1; 
console.log(typeof x); 
x = 'asdf'; 
console.log(typeof x); 

プリント:

number 
string 
+0

我々はC:あなたは、このいくつかのバリエーションを行うことができますあなたが本当に解決しようとしている問題を記述したならば、おそらく助けになるでしょう。 – jfriend00

答えて

8

あなたがtypeof演算子を使用することができます。ただし、NumberまたはStringがプリミティブでない場合は、'object'が返されます。一般に、それはあなたが望むものではありません。

var str = new String('Hello'); 
typeof str; // 'object' 

typeofnull'object'で、WebKitの中で、正規表現が'function'であることを述べています。私はtypeofの主な利点はReferenceErrorを投げずに変数をチェックすることだと思います。

変数のconstructorプロパティもチェックするか、variable instanceof Stringを使用します。ただし、複数のwindow環境では、windowコードを使用するとこれらの両方が機能しません。

タイプを決定する他の保証方法は...

var getType = function(variable) { 
    return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase(); 
} 

jsFiddleです。

2

typeofトリック時間の最もを行い

+0

私はちょうど1ヶ月前にこれを私に説明してくれたことを覚えています。 –

+0

'typeof str; // '数字'? IE5のものでなければなりません。 ;) – user113716

+0

@Patrick Whoops! – alex

0

使用JavaScriptがここtypeofを支持する機能だが、(非常に遅い)Object.prototype.toStringデフォルトは必要なときにtypeof機能

var s = "string", 
    n = 1; // number 

if(typeof s == 'string'){ 
    //do stuff for string 
} 


if(typeof n == 'number'){ 
    //do stuff for number 
} 
3

に建てられました。

このようにして、new String('x')またはnullまたは/regex/(Chrome版)の予期しない値が含まれます。


var type = (function() { 
    var toString = Object.prototype.toString, 
     typeof_res = { 
      'undefined': 'undefined', 
      'string': 'string', 
      'number': 'number', 
      'boolean': 'boolean', 
      'function': 'function' 
     }, 
     tostring_res = { 
      '[object Array]': 'array', 
      '[object Arguments]': 'arguments', 
      '[object Function]': 'function', 
      '[object RegExp]': 'regexp', 
      '[object Date]': 'date', 
      '[object Null]': 'null', 
      '[object Error]': 'error', 
      '[object Math]': 'math', 
      '[object JSON]': 'json', 
      '[object Number]': 'number', 
      '[object String]': 'string', 
      '[object Boolean]': 'boolean', 
      '[object Undefined]': 'undefined' 
     }; 
    return function type(x) { 
     var the_type = typeof_res[typeof x]; 
     return the_type && (the_type !== 'function' || (x.apply && x.call)) ? 
      the_type : 
      tostring_res[toString.call(x)] || (x ? 'object' : 'null'); 
    }; 
})(); 
type(new String('test')); // string 
type(function(){});  // function 
type(null);    // null 
type(/regex/);   // regexp 

EDIT:私はちょうど書き換えを行って、そして機能の重要な部分を削除していました。一定。

以上のコンパクト版のため

var type = (function() { 
    var i, lc, toString = Object.prototype.toString, 
     typeof_res = {}, 
     tostring_res = {}, 
     types = 'Undefined,String,Number,Boolean,Function,Array,Arguments,RegExp,Date,Null,Error,Math,JSON'.split(','); 
    for (i = 0; i < types.length; i++) { 
     lc = types[i].toLowerCase(); 
     if (i < 5) typeof_res[lc] = lc; 
     tostring_res['[object ' + types[i] + ']'] = lc; 
    } 

    return function type(x) { 
     var the_type = typeof_res[typeof x]; 
     return the_type && (the_type !== 'function' || (x.apply && x.call)) ? 
      the_type : 
      tostring_res[toString.call(x)] || (x ? 'object' : 'null'); 
    }; 
})(); 
0

その他はすでにtypeofオペレータ、およびObject.prototype.toStringの使用について話しましたが、あなたは特別int型をテストしたい場合は数の任意の並べ替えと比較しています

function isInt(n) { 
    return typeof n === "number" && n === Math.floor(n); 
} 

(。必要であれば、すべてのObject.prototype.toStringのものを挿入します)

関連する問題