Skip to content

getType (类型判断)

getType 函数用于确定给定值的类型。它能够识别多种数据类型,包括基本数据类型、对象、数组、日期、正则表达式等。

函数调用方式

javascript
getType(value)

参数说明

参数名类型描述
value*要检查类型的任意值。可以是基本数据类型、对象、数组、函数等。

返回值

返回一个字符串,表示值的类型,可以是以下之一:

  • 'null'
  • 'array'
  • 'date'
  • 'regexp'
  • 'object'
  • 'function'
  • 基本数据类型的字符串,如 'string', 'number', 'boolean', 'undefined', 'symbol', 'bigint'

异常处理

该函数不抛出异常,但对于不支持的类型(如某些特殊对象),可能返回 'object'

示例代码

基本用法

javascript
console.log(getType(null));            // 输出: 'null'
console.log(getType([]));              // 输出: 'array'
console.log(getType({}));              // 输出: 'object'
console.log(getType(new Date()));      // 输出: 'date'
console.log(getType(/regex/));         // 输出: 'regexp'
console.log(getType(function() {}));   // 输出: 'function'
console.log(getType(42));               // 输出: 'number'
console.log(getType("Hello"));         // 输出: 'string'
console.log(getType(true));            // 输出: 'boolean'

处理不同类型

javascript
console.log(getType(undefined));       // 输出: 'undefined'
console.log(getType(Symbol('sym')));   // 输出: 'symbol'
console.log(getType(BigInt(9007199254740991))); // 输出: 'bigint'

结论

getType 函数提供了一种简单且有效的方法来识别不同数据类型,适用于调试、数据验证和动态类型处理等场景。通过详细的类型检测,它帮助开发者更好地理解和处理JavaScript中的数据。