typeof 操作符
你可以使用 typeof 操作符来查看 JavaScript 变量的数据类型。
实例
typeof"John" // 返回 string
typeof3.14 // 返回 number
typeof NaN // 返回 number
typeoffalse // 返回 boolean
typeof [1,2,3,4] // 返回 object
typeof {name:'John', age:34} // 返回 object
typeofnew Date() // 返回 object
typeoffunction () {} // 返回 function
typeof myCar // 返回 undefined (如果 myCar 没有声明)
typeofnull // 返回 object
请注意:
- NaN 的数据类型是 number
- 数组(Array)的数据类型是 object
- 日期(Date)的数据类型为 object
- null 的数据类型是 object
- 未定义变量的数据类型为 undefined
如果对象是 JavaScript Array 或 JavaScript Date ,我们就无法通过 typeof 来判断他们的类型,因为都是 返回 object。