在JavaScript中,变量未经声明就使用,系统是会报错的。但是,typeof却是js中有且仅有的一个特例。
typeof的作用就是用来 区分数据的类型 的
首先,先说typeof的使用方法(语法)(以判断n的数据类型为例)
用法一:typeof(n)
用法二:typeof n
数据类型包括六大类:number、string、boolean、undefined、object、function
1.number
console.log(typeof(123)); -- > number
console.log(typeof(NaN)); -- > number
console.log(typeof(0)); -- > number
2.string
console.log(typeof('a')); -- > string
3.boolean
console.log(typeof(false)); -- > boolean
console.log(typeof(true)); -- > boolean
4.undefined
两种情况:
- 变量未声明时
console.log(typeof(a)); -- > undefined
- 变量的值就是undefined时
var a = undefined;
console.log(typeof(a)); -- > undefined
5.object
var a = {};//对象
console.log(typeof(a)); -- > object
var b = [];//数组
console.log(typeof(b)); -- > object
console.log(typeof(null)); -- > object //特殊的
6.function
var a = function () {}; //函数/方法
console.log(typeof(a)); -- > unfction
针对转换成布尔型是false的那六个
console.log(typeof(undefined)); -- > undefined
console.log(typeof(NaN)); -- > number
console.log(typeof("")); -- > string
console.log(typeof(null)); -- > object
console.log(typeof(false)); -- > boolean
console.log(typeof(0)); -- > number
拓展:
① console.log(typeof(a)); -- > undefined
② console.log(typeof(undefined)); -- > undefined
但是
③ console.log(typeof(typeof(a))); -- > string
可见,①式中,返回的undefined是一个字符串类型的。
③式就相当于是console.log(typeof('undefined')); -- > string