JavaScript中检查变量类型的最佳方法是什么?

55
<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>

问题:

我想检查 capitalized 变量的类型,所以我使用 capitalized instanceof String?但控制台显示:false,我不想尝试 capitalized instanceof FunctionObject 等方式,因为这会花费太多时间。那么,检测变量类型的最佳方法是什么?


1
因为字符串字面量不是String类型的对象。请参见typeof capitalized - zerkms
请检查我的一行代码答案 :) - minigeek
8个回答

72
最好的方法是使用typeof关键字。
typeof "hello" // "string"
typeof运算符将操作数映射为八个可能的值之一:
  • "string"
  • "number"
  • "object"
  • "function"
  • "undefined"
  • "boolean"
  • "symbol"
  • "bigint"
instanceof方法测试提供的函数的原型是否在对象的原型链中。 这篇MDN文章很好地总结了JavaScript的类型。

typeof new String("hello") == "object" 但它可以从 string 的所有相同特性中受益。最安全的做法是说 typeof x == "string" || x instance of String - Brian Nickel
我想你是正确的,尽管在实践中我几乎从未见过new String("hello")被使用。 - LandonSchropp
function 不是一个内置类型。function 是一个对象。而 null 也是一种类型。请参阅 ECMAScript 规范,第8章和第11.4.3节。 - a better oliver

21

使用 typeof();

示例:

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

所以你可以这样做:

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

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

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

var obj = new MyObj(10);

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

10

2021+ 一句答案。

我最喜欢的方式是不使用 typeof

为什么? 因为它除了布尔值、字符串、数字和函数之外,并不能提供真实的类型。

那么怎么办? 这里有一个使用Object.prototype的小实用函数

var 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

3
最好的方法是使用 typeof
typeof "blahha" 

我使用jQuery库的代码编写了一个函数,jQuery库类型方法 GitHub 链接

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

你可以将其称为getType(“Hello”)

2
getVarType方法(以下)适用于几乎所有变量。查看此fiddle。它首先使用非常快速的typeof来处理结果可靠的情况。然后,对于其他情况,它使用更昂贵的toString方法。最后,如果它正在处理命名对象(如Firefox返回的对象document.location),则会检查类似数组的对象并将它们报告为数组。
相比之下,typeof表现非常差。typeof([])返回'object',typeof(new Number())返回object。对于许多其他实际上不是对象的变量,它也返回'object'。请参见fiddle结果进行比较。
  // 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/

唯一可能的故障模式发生在测试一个空的命名数组上(例如,除了StyleSheetList之外的空可枚举DOM对象)。但是,可以根据需要将它们添加到type_of_map中。
我希望这可以帮到您!

2

capitalized 的类型为字符串


1
ES-Next版本支持BigIntSymbol

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2020-06-09
 * @modified
 *
 * @description js data type checker
 * @augments
 * @example
 * @link
 *
 */


const dataTypeChecker = (data, debug = false) => {
  const log = console.log;
  let result = ``;
  const typeString = Object.prototype.toString.call(data);
  result = typeString.replace(/\[object /gi, ``).replace(/\]/gi, ``);
  if(debug) {
    log(`true type`, result)
  }
  return result;
};



/*

export default dataTypeChecker;

export {
  dataTypeChecker,
};

*/

test

const dataTypeChecker = (data, debug = false) => {
  const log = console.log;
  let result = ``;
  const typeString = Object.prototype.toString.call(data);
  // const typeString = Object.prototype.toString.apply(data);
  result = typeString.replace(/\[object /gi, ``).replace(/\]/gi, ``);
  if(!debug) {
    log(`true type`, result)
  }
  return result;
};



const obj = {};
const func = () => {};


dataTypeChecker(NaN)
//"[object Number]"
dataTypeChecker(undefined)
//"[object Undefined]"
dataTypeChecker(true)
//"[object Boolean]"
dataTypeChecker({})
//"[object Object]"
dataTypeChecker(func)
//"[object Function]"
dataTypeChecker(obj)
//"[object Object]"
dataTypeChecker(Symbol())
//"[object Symbol]"
dataTypeChecker(null)
//"[object Null]"
dataTypeChecker(123)
//"[object Number]"
dataTypeChecker(BigInt(1n))
//"[object BigInt]"


// true type Number
// true type Undefined
// true type Boolean
// true type Object
// true type Function
// true type Object
// true type Symbol
// true type Null
// true type Number
// true type BigInt


0

 //-- difference constructor & typeof --//

 const fx = () => {}
 const arr = []
 const obj = {}
 
 console.log( fx.constructor == Function ) // true
 console.log( arr.constructor == Array ) // true
 console.log( arr.constructor == Object ) // false
 console.log( obj.constructor == Object ) // true
 console.log( obj.constructor == Array ) // false
 
 console.log( typeof obj ) // object
 console.log( typeof arr ) // object


1
你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接