javascript 在javascript中检查变量类型的最佳方法是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17440517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:20:09  来源:igfitidea点击:

what is the best way to check variable type in javascript

javascript

提问by user2507818

<script type="text/javascript">   
function saveName (firstName) {
    function capitalizeName () {
        return firstName.toUpperCase();
    }
    var capitalized = capitalizeName();console.log(capitalized instanceof String);
    return capitalized; 
}
console.log(saveName("Robert")); // Returns "ROBERT"
</script>

Question:

问题:

I want to check the type of capitalized , so I use capitalized instanceof String? But it shows: falsein console, I do not want to try capitalized instanceof Function, Object...It will take too much time, so what is the best way to detect a variable type?

我想检查大写的类型,所以我使用capitalized instanceof String? 但它显示:false在控制台中,我不想尝试capitalized instanceof FunctionObject......这将花费太多时间,那么检测变量类型的最佳方法是什么?

回答by LandonSchropp

The best way is to use the typeofkeyword.

最好的方法是使用typeof关键字。

typeof "hello" // "string"

The typeofoperator maps an operand to one of six values: "string", "number", "object", "function", "undefined"and "boolean". The instanceofmethod tests if the provided function's prototype is in the object's prototype chain.

typeof操作映射操作数以六个值之一:"string""number""object""function""undefined""boolean"。该instanceof方法测试所提供函数的原型是否在对象的原型链中。

This Wikibooks articlealong with this MDN articlesdoes a pretty good job of summing up JavaScript's types.

这篇 Wikibooks 文章这篇 MDN 文章很好地总结了 JavaScript 的类型。

回答by Fasil kk

use typeof();

利用 typeof();

example:

例子:

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

So you can do:

所以你可以这样做:

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

Keep in mind that, typeof is only good for returning the "primitive" types, number, boolean, object, string. You can also use instanceof to test if an object is of a specific type.

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

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

var obj = new MyObj(10);

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

回答by vladkras

typeof capitalized == 'string'

typeof 大写 == 'string'

回答by rab

The best way is using typeof

最好的方法是使用 typeof

typeof "blahha" 

I made a function with help of jQuery library code, jQuery library type method github link.

我在 jQuery 库代码的帮助下做了一个函数, jQuery 库类型方法 github link

var getType = (function() {

    var objToString = ({}).toString ,
        typeMap     = {},
        types = [ 
          "Boolean", 
          "Number", 
          "String",                
          "Function", 
          "Array", 
          "Date",
          "RegExp", 
          "Object", 
          "Error"
        ];

    for ( var i = 0; i < types.length ; i++ ){
        typeMap[ "[object " + types[i] + "]" ] = types[i].toLowerCase();
    };    

    return function( obj ){
        if ( obj == null ) {
            return String( obj );
        }
        // Support: Safari <= 5.1 (functionish RegExp)
        return typeof obj === "object" || typeof obj === "function" ?
            typeMap[ objToString.call(obj) ] || "object" :
            typeof obj;
    }
}());

You can call it as getType("Hello")

你可以称之为 getType("Hello")

回答by Michael Mikowski

The getVarTypemethod (below) works for almost all variables. Check out this fiddle. It first uses the very fast typeoffor cases where the results are reliable. Then it uses a more expensive toStringmethod for other cases. Finally, if it is dealing with a named object (as returned by Firefox for objects like document.location) it checks for Array-like objects and reports them as arrays.

getVarType方法(下)适用于几乎所有的变量。看看这个小提琴。它首先采用了非常快的typeof对于其中结果是可靠的情况下。然后它在其他情况下使用更昂贵的toString方法。最后,如果它正在处理一个命名对象(如 Firefox 为 document.location 之类的对象返回的),它会检查类似 Array 的对象并将它们报告为数组。

In comparison, typeofis embarrassingly poor. typeof([]) returns 'object', typeof(new Number()) returns object. It also returns 'object' for many other variables that aren't (for practical purposes) objects. See the fiddle results for a comparison.

相比之下,typeof差的很尴尬。typeof([]) 返回“对象”,typeof(new Number()) 返回对象。它还为许多其他不是(出于实际目的)对象的变量返回“对象”。请参阅小提琴结果进行比较。

  // Begin public utility /getVarType/
  // Returns 'Function', 'Object', 'Array',
  // 'String', 'Number', 'Null', 'Boolean', or 'Undefined'
  //
  getVarType = (function () {
    var typeof_map = {
      'undefined' : 'Undefined',
      'boolean'   : 'Boolean',
      'number'    : 'Number',
      'string'    : 'String',
      'function'  : 'Function',

      'Undefined' : 'Undefined',
      'Null'      : 'Null',
      'Boolean'   : 'Boolean',
      'Number'    : 'Number',
      'String'    : 'String',
      'Function'  : 'Function',
      'Array'     : 'Array',
      'StyleSheetList' : 'Array'
    };

    return function( data ) {
      var type, type_str;

      if ( data === null      ) { return 'Null'; }
      if ( data === undefined ) { return 'Undefined'; }

      type     = typeof( data );
      type_str = typeof_map[ type ];

      if ( type_str ) { return type_str; }

      type = {}.toString.call( data ).slice( 8, -1 );
      return typeof_map[ type ]
        || ( data instanceof Array ? 'Array' :
        ( data.propertyIsEnumerable(0) && data.length !== undefined
          ? 'Array' : 'Object' )
        );
    };
  }());
  // End public utility /getVarType/

The only possible failure mode happens if you are testing a named array that is empty (e.g. an empty enumerable DOM object besides the StyleSheetList). But on could add those to the type_of_map as needed.

如果您正在测试一个空的命名数组(例如,除了 StyleSheetList 之外的一个空的可枚举 DOM 对象),唯一可能的失败模式会发生。但是可以根据需要将它们添加到 type_of_map 中。

I hope that helps!

我希望这有帮助!