【问题标题】:Finding Variable Type in JavaScript在 JavaScript 中查找变量类型
【发布时间】:2010-12-16 00:19:46
【问题描述】:

在 Java 中,您可以对变量使用 instanceOfgetClass() 来找出其类型。

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

例如,我如何知道barBoolean 还是Number,还是String

function foo(bar) {
    // what do I do here?
}

【问题讨论】:

标签: javascript


【解决方案1】:

使用typeof:

> typeof "foo"
"string"
> typeof true
"boolean"
> typeof 42
"number"

所以你可以这样做:

if(typeof bar === 'number') {
   //whatever
}

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

> typeof new Boolean(false)
"object"
> typeof new String("foo")
"object"
> typeof new Number(42)
"object"

数组的类型仍然是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]"

这样您就不必区分原始值和对象。

【讨论】:

  • 使用 proto.constructor.name 一个简单的函数会有什么缺点:function getVariableType(object){ return(object.__proto__.constructor.name) ; }
  • 更新我上面列出的函数定义:function getVariableType(object){ return(object === undefined ? "Undefined" : object.__proto__.constructor.name);
  • 问题询问如何找到一个变量的类型。您的答案显示了如何查找 value 的类型。这些是完全不同的东西。
【解决方案2】:

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

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

var obj = new MyObj(10);

console.log(obj instanceof MyObj && obj instanceof Object); // outputs true

【讨论】:

  • 问题询问如何找到一个变量的类型。您的答案显示了如何查找 value 的类型。这些是完全不同的东西。
  • @JörgWMittag 想解释一下您的意思?不要评论现有答案的问题(您复制粘贴整个),如果您只是发布自己的答案来解释差异会更好
  • 已经有正确答案了:stackoverflow.com/a/20369089/2988不用自己加,答案很琐碎:JavaScript中的变量没有类型,所以不可能获取变量的类型。
  • @JörgWMittag 你在分裂头发;我们知道 variablse 在 JavaScript 中具有动态类型,并且 OP 显然试图找出变量包含的值的类型
【解决方案3】:

使用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';

【讨论】:

  • 使用Number(1), Boolean(true)... 没有问题 唯一的问题是当您使用new 并创建了一个装箱对象时,将它们用作函数实际上对于从其他类型转换很有用。 Boolean(0) === false, Number(true) === 1
  • null 呢? typeof null 是“对象”
  • 问题询问如何找到变量的类型。您的答案显示了如何找到 value 的类型。这些是完全不同的东西。
【解决方案4】:

在 Javascript 中,您可以使用 typeof 函数来做到这一点

console.log(typeof bar);

【讨论】:

  • 就像我在回答中提到的那样,typof 只会返回数字、布尔值、对象、字符串。不适用于确定任何其他类型,例如 Array、RegExp 或自定义类型。
  • 问题询问如何找到变量的类型。您的答案显示了如何找到 value 的类型。这些是完全不同的事情。此外,typeof 是运算符而不是函数。
【解决方案5】:

比其他答案更精确一点 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';
    }
}

【讨论】:

  • 还有symbols
  • ECMAScript 5.1 中没有,没有。
【解决方案6】:

我对@9​​87654321@ 如此有限感到沮丧。这是一个改进的版本:

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);
    }   
};

样本测试:

realtypeof( '' ) // "string"
realtypeof( new String('') ) // "[object String]"
Object.prototype.toString.call("foo bar") //"[object String]" 

【讨论】:

  • 问题询问如何找到变量的类型。您的答案显示了如何找到 value 的类型。这些是完全不同的东西。
【解决方案7】:

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

function getTypeName(val) {
    return {}.toString.call(val).slice(8, -1);
}

这里我们使用 '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"

如果你需要一个类名,你可以使用:

instance.constructor.name

例子:

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

function MyClass() {}
let my = new MyClass();
my.constructor.name         // "MyClass"

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

【讨论】:

  • 问题询问如何找到变量的类型。您的答案显示了如何查找 value 的类型。这些是完全不同的东西。
  • @JörgWMittag 您可以将变量传递给getTypeName 函数,它将正常工作。示例:let a = 42; getTypeName(a) // "Number"
  • 但这将仍然为您提供分配给变量的值的类型。它不会给你变量的类型。然而,这个问题明确地询问如何找到变量的类型,而不是值。
  • 值类型和具有该值的变量有什么区别?当您为变量赋值时,它们将始终具有相同的类型。在 JS 中,没有赋值就无法定义具有某种类型的变量。
  • @JörgWMittag 我也对您在此处的评论和其他答案感到困惑。如果不是基于分配给它的值,变量的类型应该是什么?请注意,OP 与 Java 相提并论,getClass()instanceofvalue 起作用,而不管它是用什么类型声明的。例如,对于Object foo = "hello";,调用foo.getClass() 将产生Class<java.lang.String>。调用foo instanceof String 同样会产生true
【解决方案8】:

在 JavaScript 中,一切都是对象

console.log(type of({}))  //Object
console.log(type of([]))  //Object

要获得 Real 类型,请使用此

console.log(Object.prototype.toString.call({}))   //[object Object]
console.log(Object.prototype.toString.call([]))   //[object Array]

希望对你有帮助

【讨论】:

  • 问题询问如何找到一个变量的类型。您的答案显示了如何查找 value 的类型。这些是完全不同的东西。
【解决方案9】:

许多人建议使用 typeOf,但忘记了 JS qwirks。 这是您可以使用的一个线性实用程序函数

const trueTypeOf = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()

输出:

trueTypeOf([]); // array
trueTypeOf({}); // object
trueTypeOf(''); // string
trueTypeOf(new Date()); // date
trueTypeOf(1); // number
trueTypeOf(function () {}); // function.
trueTypeOf(/test/i); // regexp
trueTypeOf(true); // boolean
trueTypeOf(null); // null
trueTypeOf(); // undefined

【讨论】:

    【解决方案10】:

    这是完整的解决方案。

    您也可以将它用作项目中的 Helper 类。

    "use strict";
    /**
     * @description Util file
     * @author Tarandeep Singh
     * @created 2016-08-09
     */
    
    window.Sys = {};
    
    Sys = {
      isEmptyObject: function(val) {
        return this.isObject(val) && Object.keys(val).length;
      },
      /** This Returns Object Type */
      getType: function(val) {
        return Object.prototype.toString.call(val);
      },
      /** This Checks and Return if Object is Defined */
      isDefined: function(val) {
        return val !== void 0 || typeof val !== 'undefined';
      },
      /** Run a Map on an Array **/
      map: function(arr, fn) {
        var res = [],
          i = 0;
        for (; i < arr.length; ++i) {
          res.push(fn(arr[i], i));
        }
        arr = null;
        return res;
      },
      /** Checks and Return if the prop is Objects own Property */
      hasOwnProp: function(obj, val) {
        return Object.prototype.hasOwnProperty.call(obj, val);
      },
      /** Extend properties from extending Object to initial Object */
      extend: function(newObj, oldObj) {
        if (this.isDefined(newObj) && this.isDefined(oldObj)) {
          for (var prop in oldObj) {
            if (this.hasOwnProp(oldObj, prop)) {
              newObj[prop] = oldObj[prop];
            }
          }
          return newObj;
        } else {
          return newObj || oldObj || {};
        }
      }
    };
    
    // This Method will create Multiple functions in the Sys object that can be used to test type of
    ['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Object', 'Array', 'Undefined']
    .forEach(
      function(name) {
        Sys['is' + name] = function(obj) {
          return toString.call(obj) == '[object ' + name + ']';
        };
      }
    );
    <h1>Use the Helper JavaScript Methods..</h1>
    <code>use: if(Sys.isDefined(jQuery){console.log("O Yeah... !!");}</code>

    对于可导出的 CommonJs 模块或 RequireJS 模块......

    "use strict";
    
    /*** Helper Utils ***/
    
    /**
     * @description Util file :: From Vault
     * @author Tarandeep Singh
     * @created 2016-08-09
     */
    
    var Sys = {};
    
    Sys = {
        isEmptyObject: function(val){
            return this.isObject(val) && Object.keys(val).length;
        },
        /** This Returns Object Type */
        getType: function(val){
            return Object.prototype.toString.call(val);
        },
        /** This Checks and Return if Object is Defined */
        isDefined: function(val){
            return val !== void 0 || typeof val !== 'undefined';
        },
        /** Run a Map on an Array **/
        map: function(arr,fn){
            var res = [], i=0;
            for( ; i<arr.length; ++i){
                res.push(fn(arr[i], i));
            }
            arr = null;
            return res;
        },
        /** Checks and Return if the prop is Objects own Property */
        hasOwnProp: function(obj, val){
            return Object.prototype.hasOwnProperty.call(obj, val);
        },
        /** Extend properties from extending Object to initial Object */
        extend: function(newObj, oldObj){
            if(this.isDefined(newObj) && this.isDefined(oldObj)){
                for(var prop in oldObj){
                    if(this.hasOwnProp(oldObj, prop)){
                        newObj[prop] = oldObj[prop];
                    }
                }
                return newObj;
            }else {
                return newObj || oldObj || {};
            }
        }
    };
    
    /**
     * This isn't Required but just makes WebStorm color Code Better :D
     * */
    Sys.isObject
        = Sys.isArguments
        = Sys.isFunction
        = Sys.isString
        = Sys.isArray
        = Sys.isUndefined
        = Sys.isDate
        = Sys.isNumber
        = Sys.isRegExp
        = "";
    
    /** This Method will create Multiple functions in the Sys object that can be used to test type of **/
    
    ['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Object', 'Array', 'Undefined']
        .forEach(
            function(name) {
                Sys['is' + name] = function(obj) {
                    return toString.call(obj) == '[object ' + name + ']';
                };
            }
        );
    
    
    module.exports = Sys;
    

    目前在公共 git 存储库中使用。 Github Project

    现在您可以在 Sys.js 文件中导入此 Sys 代码。 那么你可以使用这个 Sys 对象函数来找出 JavaScript 对象的类型

    您还可以检查对象是否已定义或类型是否为函数或对象是否为空...等。

    • Sys.isObject
    • Sys.isArguments
    • Sys.isFunction
    • Sys.isString
    • Sys.isArray
    • Sys.isUndefined
    • Sys.isDate
    • Sys.isNumber
    • Sys.isRegExp

    举例

    var m = function(){};
    Sys.isObject({});
    Sys.isFunction(m);
    Sys.isString(m);
    
    console.log(Sys.isDefined(jQuery));
    

    【讨论】:

    • 问题询问如何找到一个变量的类型。您的答案显示了如何查找 value 的类型。这些是完全不同的东西。
    【解决方案11】:

    这是一个有用的解决方案:

        newTypeOf = (value) => {
            return Object.prototype.toString.call(value).split(' ')[1].split(']')[0].toString()
        } 
    
        newTypeOf(12) // Number
        newTypeOf('') // String
        newTypeOf([]) // Array 
        newTypeOf({}) // Number 
        newTypeOf(null) // Null 
        newTypeOf(undefined) // Undefined
        newTypeOf(()=>{}) // Function
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-02
      • 2020-11-07
      • 2012-10-06
      • 1970-01-01
      • 1970-01-01
      • 2015-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多