JavaScript 数据类型判断的四种方式与最佳实践

作者:小括号时间:2026-10-26 02:43:35浏览:120

JavaScript 包含八种数据类型,准确判断类型是开发中的常见需求。本文详细解析 typeof、instanceof、Object.prototype.toString.call() 以及 constructor 四种判断方式。重点推荐 Object.prototype.toString.call(),因其能准确识别所有内置类型,是处理复杂对象类型的最佳实践。

JavaScript 语言目前定义了八种基本数据类型。

值类型

  • Number
  • Null
  • Undefined
  • String
  • Symbol
  • Boolean
  • BigInt

引用类型

  • Object
  • Array
  • Function

在 JavaScript 中判断数据类型,主要可以使用以下四种方法。

第一种方式:使用 typeof 运算符。

typeof null   ---> "object"

 typeof undefined  ---> "undefined"

 typeof true | false  ---> 'boolean'

 typeof 42    ---> 'number'

 typeof "42" ---> 'string'

 typeof { name : '1'} | []  ---> 'object'

 typeof Symbol    ---> 'symbol'

 typeof ()=>{}       ---> 'function'

 typeof void 0      ---> 'undefined'

第二种方式:使用 instanceof 运算符,但这种方式仅适用于判断对象类型。

instanceof 运算符用于检测一个构造函数的 prototype 属性所指向的对象,是否存在于另一个要检测对象的原型链上。

关于 JavaScript 中 instanceof 运算符的详细介绍,请参阅相关技术文档。

比如 :
var arr = [] ;
arr instanceof Array   ---> true
null instanceof Object ---> false
[function] instanceof Object | Function  --> true

第三种方式:使用 Object.prototype.toString.call(),这种方式可以检测出所有的数据类型,也是官方推荐的最佳实践方式。

这是因为 toString 是 Object 的原型方法,而 Array、Function 等都是 Object 的实例,它们都重写了 toString 方法,返回表示类型的字符串。

Object.prototype.toString.call(null)  --->  [object Null]

 Object.prototupe.toString.call(undefined)  ---> [object Undefined]

 Object.prototype.toString.call(123)  ---> [object Number]

 Object.prototype.toString.call(true) ---> [object Boolean]

 Object.prototype.toString.call('123') ---> [object String]

 Object.prototype.toString.call({})    ---> [object Object]

 Object.prototype.toString.call([])    ---> [object Array]

 Object.prototype.toString.call(Math) ---> [object Math]

 Object.prototype.toString.call(function(){}) ---> [object Function]

 Objdec.prototype.toString.call(new Date)  ---> [object Date]

 Object.prototype.toString.call(Symbol())   ---> [object Symbol]

第四种方式:通过 constructor 属性判断对象的构造函数。

1.  null 是js 原型链的起点,没有构造函数

  2. undefined 没有构造函数

  3. [].constructor  === Array  ---> true

  4. [string].constructor === String

  5. [object].constructor === object

  6. [number].constructor === Number

  7. [symbol].constructor === Symbol

  8. [function].constructor === Function

  9. [new Date].constructor === Date

  10. [RegExp].constructor === RegExp

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

作者最新文章