在 JavaScript 中获取 变量 的 数据类型 使用 typeof 操作符,typeof 操作符返回一个 字符串,表示未经计算的操作数的类型。
typeof operand
typeof(operand)
使用 typeof 获取 对象 operand 的数据类型,typeof 有两种形式,一种是不加小括号,一种是带小括号。
参数 | 说明 |
---|---|
operand | 要获取数据类型的对象 |
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>
程序运行后,控制台输出如下:
我们首先使用 var 关键字,定义了五个变量,五个变量的数据类型分别为:数字、字符串、浮点数、布尔 与 undefined。
最后,我们使用 typeof 的两种形式来获取五个变量的数据类型。
我们可以使用 == 将变量的数据类型与字符串的数据类型进行比较
<!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>
程序运行后,控制台输出如下:
我们使用 typeof 获取的变量的数据类型可以与字符串的数据类型使用 == 进行比较。
在 JavaScript 中获取变量的数据类型使用 typeof 操作符,typeof 操作符返回一个字符串,表示未经计算的操作数的类型。