JavaScript获取变量类型typeof

JavaScript获取变量类型

JavaScript 中获取 变量数据类型 使用 typeof 操作符,typeof 操作符返回一个 字符串,表示未经计算的操作数的类型。

JavaScript typeof详解

语法

typeof operand typeof(operand)

说明

使用 typeof 获取 对象 operand 的数据类型,typeof 有两种形式,一种是不加小括号,一种是带小括号。

参数

参数 说明
operand 要获取数据类型的对象

返回值

typeof 操作符返回一个字符串,表示未经计算的操作数的类型。

案例

JavaScript typeof获取变量类型

使用 typeof 获取变量的数据类型

<!DOCTYPE html> <html> <head> <title>使用 typeof 获取变量的数据类型</title> <script type="text/javascript"> console.log("嗨客网(www.haicoder.net)"); var num = 1024; var str = "HaiCoder"; var score = 99.5; var isPass = false; var undef = undefined; console.log("type num =", typeof num); console.log("type str =", typeof str); console.log("type score =", typeof(score)); console.log("type isPass =", typeof(isPass)); console.log("type undef =", typeof(undef)); </script> </head> </html>

程序运行后,控制台输出如下:

39_javascript typeof.png

我们首先使用 var 关键字,定义了五个变量,五个变量的数据类型分别为:数字字符串浮点数布尔undefined

最后,我们使用 typeof 的两种形式来获取五个变量的数据类型。

JavaScript变量类型判断

我们可以使用 == 将变量的数据类型与字符串的数据类型进行比较

<!DOCTYPE html> <html> <head> <title>JavaScript变量类型判断</title> <script type="text/javascript"> console.log("嗨客网(www.haicoder.net)"); var num = 1024; var str = "HaiCoder"; var isPass = false; if (typeof num === "number"){ console.log("type num is Number"); }else{ console.log("type num is not Number"); } if (typeof str === "string"){ console.log("type str is string"); }else{ console.log("type str is not string"); } if (typeof isPass === "boolean"){ console.log("type isPass is boolean"); }else{ console.log("type isPass is not boolean"); } </script> </head> </html>

程序运行后,控制台输出如下:

40_javascript typeof.png

我们使用 typeof 获取的变量的数据类型可以与字符串的数据类型使用 == 进行比较。

JavaScript获取变量类型总结

在 JavaScript 中获取变量的数据类型使用 typeof 操作符,typeof 操作符返回一个字符串,表示未经计算的操作数的类型。