聊一聊JavaScript中typeof那点事儿

js是一门脚本化语言,它在声明变量时不需确定变量的类型,js在运行时会自动判断。那么怎么判断变量的类型呢?js提供了typeof运算符,用来判断变量是什么类型。

typeof的语法:

方式一:
typeof(表达式)
(对表达式做运算)
方式二:
typeof 变量名
(对变量做运算)

typeof六大类返回值:

类型 结果
String “string”
Number “number”
Boolean “boolean”
Undefined “undefined”
Object “object”
Function函数对象 “function”

1 . string

字符类型的值或变量

alert(typeof('a'));// string
alert(typeof("")); // string 

2 . number

数字类型的值或变量

alert(typeof(0));       //number
alert(typeof(121));     //number
alert(typeof(NaN));     //number
alert(typeof(Math.LN2));//number
alert(typeof(Infinity));//number

3 . boolean

布尔类型的值或变量

alert(typeof(flase)); //boolean
alert(typeof(true));  //boolean

4 . undefined

未定义的值或变量

//变量未声明时
alert(typeof(a)); //undefined

//变量值就是undefined
var a = undefined;
alert(typeof(a));  //undefined

5 . object

对象类型的值,变量或null

var a = {};//对象
alert(typeof(a)); //object

var b = [123];//数组
alert(typeof(b)); //object

alert(typeof(null); //object 这是个特例将null作为object类型处理

6 . function

函数类型的值或变量

alert(typeof(function(){});//函数方法
alert(typeof(Math.sin));
发布了41 篇原创文章 · 获赞 49 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/wls666/article/details/88990522