编写javascript代码的时候常常要判断变量,字面量的类型,可以用typeof,instanceof,Array.isArray(),等方法,究竟哪一种最方便,最实用,最省心呢?本问探讨这个问题。

1. typeof

1.1 语法

typeof返回一个字符串,表示未经计算的操作数的类型。

语法:typeof(operand) | typeof operand
参数:一个表示对象或原始值的表达式,其类型将被返回
描述:typeof可能返回的值如下:

类型 结果
Undefined “undefined”
Null “object”
Boolean “boolean”
Number “number”
Bigint “bigint”
String “string”
Symbol “symbol”
宿主对象(由JS环境提供) 取决于具体实现
Function对象 “function”
其他任何对象 “object”

 

 

 

 

 

 

 

 

从定义和描述上来看,这个语法可以判断出很多的数据类型,但是仔细观察,typeof null居然返回的是“object”,让人摸不着头脑,下面会具体介绍,先看看这个效果:

复制代码
    // 数值    console.log(typeof 37) // number    console.log(typeof 3.14) // number    console.log(typeof(42)) // number    console.log(typeof Math.LN2) // number    console.log(typeof Infinity) // number    console.log(typeof NaN) // number 尽管它是Not-A-Number的缩写,实际NaN是数字计算得到的结果,或者将其他类型变量转化成数字失败的结果    console.log(Number(1)) //number Number(1)构造函数会把参数解析成字面量    console.log(typeof 42n) //bigint    // 字符串    console.log(typeof '') //string    console.log(typeof 'boo') // string    console.log(typeof `template literal`) // string    console.log(typeof '1') //string 内容为数字的字符串仍然是字符串    console.log(typeof(typeof 1)) //string,typeof总是返回一个字符串    console.log(typeof String(1)) //string String将任意值转换成字符串    // 布尔值    console.log(typeof true) // boolean    console.log(typeof false) // boolean    console.log(typeof Boolean(1)) // boolean Boolean会基于参数是真值还是虚值进行转换    console.log(typeof !!(1)) // boolean 两次调用!!操作想短语Boolean()    // Undefined    console.log(typeof undefined) // undefined    console.log(