typeof操作符

背景

JavaScript支持中支持5种简单数据类型:Undefined,Null,Boolean,Number和String。还有1种复杂数据类型:Object。JavaScript不支持任何自定义数据类型的机制,而所有数据类型都将属于上述6种类型中的一种。

typeof操作符

JavaScript提供了一种手段将判定给定变量的数据类型,它便是typeof操作符。typeof操作符可能返回下列的某个字符串:

  • “boolean":如果变量是布尔值
  • "function":如果变量是函数
  • "number”:如果变量是数值
  • “object":如果变量是对象或null
  • "string”:如果变量是字符串
  • "undefined":如果 变量未定义

typeof应用实例

<html>
<head>
<title>Example</title>
</head>
<body>
	<script type="text/javascript">
		var names = new Array("Mike", "Sue");
		document.write("typeof(1): " + typeof (1) + "<br>");
		document.write("typeof(\"123\"): " + typeof ("123") + "<br>");
		document.write("typeof(true): " + typeof (true) + "<br>");
		document.write("typeof(window): " + typeof (window) + "<br>");
		document.write("typeof(null): " + typeof (null) + "<br>");
		document.write("typeof(eval): " + typeof (eval) + "<br>");
		document.write("typeof(Date): " + typeof (Date) + "<br>");
		document.write("typeof(Array): " + typeof (Array) + "<br>");
		document.write("typeof(sss): " + typeof (sss) + "<br>");
		document.write("typeof(undefined): " + typeof (undefined) + "<br>");
		document.write("typeof(names): " + typeof (names) + "<br>");
	</script>
</body>
</html>

注意:typeof是一个操作符而非函数,因此,上述例子中的括号不是必须的。最终测试结果如下:

typeof(1): number
typeof("123"): string
typeof(true): boolean
typeof(window): object
typeof(null): object
typeof(eval): function
typeof(Date): function
typeof(Array): function
typeof(sss): undefined
typeof(undefined): undefined
typeof(names): object

typeof为何区分函数与对象

从技术角度上分析,函数在JavaScript中是一种对象,不是一种数据类型。但是,函数本身确实存在一些特殊的属性,因此通过typeof操作符来区分函数与其它对象是非常必要的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值