JS 判断变量类型(判断数据类型、typeof)

本文深入解析JavaScript中的数据类型,包括基本类型如字符串、数字、布尔值,以及复杂类型如对象、数组、函数和日期的判断方法。通过实例展示了typeof操作符、constructor属性的使用,以及如何判断一个变量是否为数组或日期。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数据类型

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>阿西吧</title>
</head>
<body>

<p> typeof 操作符返回变量、对象、函数、表达式的类型。</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 
    typeof "john" + "<br>" +
    typeof 3.14 + "<br>" +
    typeof NaN + "<br>" +
    typeof false + "<br>" +
    typeof [1,2,3,4] + "<br>" +
    typeof {name:'john', age:34} + "<br>" +
    typeof new Date() + "<br>" +
    typeof function () {} + "<br>" +
    typeof myCar + "<br>" +
    typeof null;
</script>

</body>
</html>

运行结果

typeof 操作符返回变量、对象、函数、表达式的类型。

string
number
number
boolean
object
object
object
function
undefined
object

判断数据类型

constructor 属性

constructor 属性返回所有 JavaScript 变量的构造函数。

实例

"John".constructor                 // 返回函数 String()  { [native code] }
(3.14).constructor                 // 返回函数 Number()  { [native code] }
false.constructor                  // 返回函数 Boolean() { [native code] }
[1,2,3,4].constructor              // 返回函数 Array()   { [native code] }
{name:'John', age:34}.constructor  // 返回函数 Object()  { [native code] }
new Date().constructor             // 返回函数 Date()    { [native code] }
function () {}.constructor         // 返回函数 Function(){ [native code] }

判断数组

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>啊洗吧</title>
</head>
<body>

<p>判断是否为数组。</p>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = isArray(fruits);
function isArray(myArray) {
    return myArray.constructor.toString().indexOf("Array") > -1;
}
</script>

</body>
</html>

运行结果

判断是否为数组。

true

判断日期

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>啊洗吧</title>
</head>
<body>

<p>判断是否为日期。</p>
<p id="demo"></p>
<script>
var myDate = new Date();
document.getElementById("demo").innerHTML = isDate(myDate);
function isDate(myDate) {
    return myDate.constructor.toString().indexOf("Date") > -1;
}
</script>

</body>
</html>

运行结果

判断是否为日期。

true

undefined

在 JavaScript 中, undefined 是一个没有设置值的变量。

typeof 一个没有值的变量会返回 undefined

实例

var person;                  // 值为 undefined(空), 类型是undefined

null

在 JavaScript 中 null 表示 "什么都没有"。

null是一个只有一个值的特殊类型。表示一个空对象引用。

你可以设置为 null 来清空对象:

实例

var person = null;           // 值为 null(空), 但类型为对象

undefined 和 null 的区别

实例

null 和 undefined 的值相等,但类型不等:

typeof undefined             // undefined
typeof null                  // object
null === undefined           // false
null == undefined            // true

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

墨痕诉清风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值