关于JavaScript中的typeOf的用法

154 阅读3分钟

前言

typeof 运算符是 javascript 的基础知识点,尽管它存在一定的局限性,但在前端js的实际编码过程中,仍然是使用比较多的类型判断方式。
因此,掌握该运算符的特点,对于写出好的代码,就会起到很大的帮助作用。

typeof 返回一个字符串,表示该操作值的数据类型,基本语法:

typeof operand
typeof(operand)

可能返回的类型字符串有:string, boolean, number, bigint, symbol, undefined, function, object。

返回类型

将根据可能的返回类型,进行以下的分类介绍,对typeof的使用方法一网打尽。

string 和 boolean

字符串、布尔值分别返回 'string'、'boolean'。
包括 String() 和 Boolean()。

typeof '1' // 'string'
typeof String(1) // 'string'
typeof true // 'boolean'
typeof Boolean() // 'boolean'

number 和 bigint

数字返回 'number',包括 Number()、NaN 和 Infinity 等,以及 Math 对象下的各个数学常量值。
BigInt 数字类型值返回 'bigint',包括 BigInt(1)。

typeof 1 // 'number'
typeof NaN // 'number'
typeof Math.PI // 'number'
typeof 42n // 'bigint'
typeof BigInt(1) // 'bigint'

symbol

symbol 值返回 'symbol',包括 Symbol()。

typeof Symbol() // 'symbol'
typeof Symbol('foo') // 'symbol'
typeof Symbol.iterator // 'symbol'

undefined

undefined 本身返回 'undefined'。
不存在的,或者定义了但未赋初值的变量,都会返回 undefined。
还有 document.all 等浏览器的非标准特性。

typeof undefined // 'undefined'
typeof ttttttt // 'undefined'
typeof document.all // 'undefined'

function 函数返回 'function'。 包括使用es6的 class 类声明的。 还有各个内置对象 String、Number、BigInt、Boolean、RegExp、Error、Object、Date、Array、Function、Symbol 本身。 以及 Function(),new Function()。

function func () {}
typeof func // 'function'
typeof class cs {} // 'function'
typeof String // 'function'
typeof RegExp // 'function'
typeof new Function() // 'function'

object

对象、数组、null、正则表达式,都返回 'object'。
包括 Math、JSON 对象本身。
还有使用 new 操作符的数据,除了 Function 以外。

typeof {} // 'object'
typeof [] // 'object'
typeof null // 'object'
typeof /d/ // 'object'
typeof Math // 'object'
typeof new Number(1) // 'object'

其他 关于其他大部分的 javascript关键字,得到的结果值都是 'object' 或 'function'。 注:多数小写字母开头的是对象 object,多数大写字母开头的都是方法 function。常见的明确知道的方法不算,如 alert,prompt 等方法

除此以外,还有各js环境下具体实现的宿主对象。

常见问题

引用错误

在 let 和 const 块级作用域变量定义之前,使用 typeof 会抛错 ReferenceError。
因为块级作用域变量,会在头部形成 暂存死区,直到被初始化,否则会报引用错误。

typeof t
let t = 1
// VM327:1 Uncaught ReferenceError: t is not defined
//    at <anonymous>:1:1

如果是使用 var 定义变量,不会报错,返回 'undefined' 。 有变量提升,不会形成暂时死区。

typeof null 对于 "typeof null === 'object'" ,记住即可,可能的解释: 在JavaScript 最初的实现中,JavaScript 中的值是由一个表示类型的标签和实际数据值表示的。对象的类型标签是 0。由于null代表的是空指针(大多数平台下值为 0x00),因此,null 的类型标签是 0,typeof null 也因此返回 'object'。

typeof 的局限性 typeof 的局限性,在于无法精确判断出 null、数组、对象、正则 的类型。 所以如果要精准判断,还需要使用其他技术手段,或组合判断。 如下,判断数组类型:

Object.prototype.toString.call([]) // '[object Array]'
[] instanceof Array // true
[].constructor === Array // true

其中,Object.prototype.toString.call 是javascript中用于准确判断数据类型的通用手段。