在JavaScript中查找变量类型

Tom*_*ker 130 javascript

在Java中,您可以使用instanceOfgetClass()在变量上查找其类型.

如何在JavaScript中找出不是强类型的变量类型?

例如,我如何知道bara是a Boolean还是a Number,还是a String

function foo(bar) {
    // what do I do here?
}
Run Code Online (Sandbox Code Playgroud)

Fel*_*ing 224

用途typeof:

> typeof "foo"
"string"
> typeof true
"boolean"
> typeof 42
"number"
Run Code Online (Sandbox Code Playgroud)

所以你可以这样做:

if(typeof bar === 'number') {
   //whatever
}
Run Code Online (Sandbox Code Playgroud)

但要小心,如果用它们的对象包装器定义这些原语(你永远不应该这样做,尽可能使用文字):

> typeof new Boolean(false)
"object"
> typeof new String("foo")
"object"
> typeof new Number(42)
"object"
Run Code Online (Sandbox Code Playgroud)

数组的类型仍然是object.在这里你真的需要instanceof操作员.

更新:

另一个有趣的方法是检查输出Object.prototype.toString:

> Object.prototype.toString.call([1,2,3])
"[object Array]"
> Object.prototype.toString.call("foo bar")
"[object String]"
> Object.prototype.toString.call(45)
"[object Number]"
> Object.prototype.toString.call(false)
"[object Boolean]"
> Object.prototype.toString.call(new String("foo bar"))
"[object String]"
> Object.prototype.toString.call(null)
"[object Null]"
> Object.prototype.toString.call(/123/)
"[object RegExp]"
> Object.prototype.toString.call(undefined)
"[object Undefined]"
Run Code Online (Sandbox Code Playgroud)

有了它,你不必区分原始值和对象.


Jua*_*des 29

typeof仅适用于返回"原始"类型,如数字,布尔值,对象,字符串和符号.您还可以使用它instanceof来测试对象是否属于特定类型.

function MyObj(prop) {
  this.prop = prop;
}

var obj = new MyObj(10);

console.log(obj instanceof MyObj && obj instanceof Object); // outputs true
Run Code Online (Sandbox Code Playgroud)

  • @JörgWMittag 你正在吹毛求疵;我们知道变量在 JavaScript 中具有动态类型,并且 OP 显然试图找出变量包含的值的类型 (2认同)

kri*_*ngh 21

使用type:

// 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';
Run Code Online (Sandbox Code Playgroud)


waj*_*jiw 11

在Javascript中,您可以使用typeof函数来完成此操作

function foo(bar){
  alert(typeof(bar));
}
Run Code Online (Sandbox Code Playgroud)

  • 就像我在回答中提到的那样,typof只会返回数字,布尔值,对象,字符串.对于确定任何其他类型(如Array,RegExp或自定义类型)无用. (3认同)

小智 7

要比其他答案更精确一点ECMAScript-5.1(有些人可能会说迂腐):

在JavaScript中,变量(和属性)没有类型:值.此外,只有6种类型的值:Undefined,Null,Boolean,String,Number和Object.(在技术上,也有7"规范型",但你不能将那些类型的值存储为变量对象的属性或值 - 他们只有规范本身内使用,定义语言是如何工作的值.你可以明确地操纵我所列出的6种类型.)

当它想要谈论"x的类型"时,规范使用符号"Type(x)".这只是规范中使用的符号:它不是该语言的一个特征.

正如其他答案所表明的那样,在实践中,您可能想要了解的不仅仅是值的类型 - 特别是当类型是Object时.无论如何,为了完整起见,这里是一个简单的Type(x)JavaScript实现,因为它在规范中使用:

function Type(x) { 
    if (x === null) {
        return 'Null';
    }

    switch (typeof x) {
    case 'undefined': return 'Undefined';
    case 'boolean'  : return 'Boolean';
    case 'number'   : return 'Number';
    case 'string'   : return 'String';
    default         : return 'Object';
    }
}
Run Code Online (Sandbox Code Playgroud)


Tom*_*und 6

我感到typeof如此有限的令人沮丧。这是一个改进的版本:

var realtypeof = function (obj) {
    switch (typeof(obj)) {
        // object prototypes
        case 'object':
            if (obj instanceof Array)
                return '[object Array]';
            if (obj instanceof Date)
                return '[object Date]';
            if (obj instanceof RegExp)
                return '[object regexp]';
            if (obj instanceof String)
                return '[object String]';
            if (obj instanceof Number)
                return '[object Number]';

            return 'object';
        // object literals
        default:
            return typeof(obj);
    }   
};
Run Code Online (Sandbox Code Playgroud)

样品测试:

realtypeof( '' ) // "string"
realtypeof( new String('') ) // "[object String]"
Object.prototype.toString.call("foo bar") //"[object String]" 
Run Code Online (Sandbox Code Playgroud)


Web*_*her 6

对于内置 JS 类型,您可以使用:

function getTypeName(val) {
    return {}.toString.call(val).slice(8, -1);
}
Run Code Online (Sandbox Code Playgroud)

这里我们使用“Object”类中的“toString”方法,该方法的工作方式与其他类型的相同方法不同。

例子:

// Primitives
getTypeName(42);        // "Number"
getTypeName("hi");      // "String"
getTypeName(true);      // "Boolean"
getTypeName(Symbol('s'))// "Symbol"
getTypeName(null);      // "Null"
getTypeName(undefined); // "Undefined"

// Non-primitives
getTypeName({});            // "Object"
getTypeName([]);            // "Array"
getTypeName(new Date);      // "Date"
getTypeName(function() {}); // "Function"
getTypeName(/a/);           // "RegExp"
getTypeName(new Error);     // "Error"
Run Code Online (Sandbox Code Playgroud)

如果您需要类名,可以使用:

instance.constructor.name
Run Code Online (Sandbox Code Playgroud)

例子:

({}).constructor.name       // "Object"
[].constructor.name         // "Array"
(new Date).constructor.name // "Date"

function MyClass() {}
let my = new MyClass();
my.constructor.name         // "MyClass"
Run Code Online (Sandbox Code Playgroud)

但这个功能是在ES2015中添加的。