typeof运算符是一元运算符,位于其单个操作数(可以是任何类型)之前。它的值是一个字符串,指示操作数的数据类型。如果typeof运算符的操作数是数字,字符串或布尔值,则其计算结果为“数字”,“字符串”或“布尔值”,并根据计算结果返回true或false。
这是typeof运算符的返回值列表。
类型 | 由typeof返回的字符串 |
---|---|
数 | “数” |
串 | “串” |
布尔型 | “布尔值” |
目的 | “目的” |
功能 | “功能” |
未定义 | “未定义” |
空值 | “目的” |
以下代码显示了如何实现typeof运算符-
<html> <body> <script> var a = 10; var b = "String"; var linebreak = "<br />"; result = (typeof b == "string" ? "B is String" : "Bis Numeric"); document.write("Result => "); document.write(result); document.write(linebreak); result = (typeof a == "string" ? "A is String" : "Ais Numeric"); document.write("Result => "); document.write(result); document.write(linebreak); </script> </body> </html>