检测数据类型的几种方法

1. 使用 typeof 操作符

typeof 操作符可以用来判断一个变量的基本类型

let a = 42;
console.log(typeof a);  // 输出 "number"

a = "Hello";
console.log(typeof a);  // 输出 "string"

a = true;
console.log(typeof a);  // 输出 "boolean"

a = {};
console.log(typeof a);  // 输出 "object"

a = [];
console.log(typeof a);  // 输出 "object"(数组被认为是对象)

a = null;
console.log(typeof a);  // 输出 "object"(特例,null 被认为是空对象引用)

a = undefined;
console.log(typeof a);  // 输出 "undefined"

a = function() {};
console.log(typeof a);  // 输出 "function"

2. 使用 Array.isArray() 判断数组

Array.isArray() 是用来判断一个变量是否为数组的方法。

let arr = [1, 2, 3];
console.log(Array.isArray(arr));  // 输出 true

let notArr = {};
console.log(Array.isArray(notArr));  // 输出 false

3. 使用 instanceof 操作符

instanceof 操作符用来检测构造函数的原型链中是否存在某个对象的原型。

let date = new Date();
console.log(date instanceof Date);  // 输出 true

let obj = {};
console.log(obj instanceof Object);  // 输出 true

let arr = [];
console.log(arr instanceof Array);  // 输出 true

let num = 42;
console.log(num instanceof Number);  // 输出 false(因为 42 是原始类型,不是 Number 对象)

4. 使用 Object.prototype.toString.call() 方法

这是一种比较通用和精确的方法,可以判断 JavaScript 中几乎所有类型的变量。

let obj = {};
console.log(Object.prototype.toString.call(obj));  // 输出 "[object Object]"

let arr = [];
console.log(Object.prototype.toString.call(arr));  // 输出 "[object Array]"

let num = 42;
console.log(Object.prototype.toString.call(num));  // 输出 "[object Number]"

let str = "Hello";
console.log(Object.prototype.toString.call(str));  // 输出 "[object String]"

let bool = true;
console.log(Object.prototype.toString.call(bool));  // 输出 "[object Boolean]"

let date = new Date();
console.log(Object.prototype.toString.call(date));  // 输出 "[object Date]"

let func = function() {};
console.log(Object.prototype.toString.call(func));  // 输出 "[object Function]"

let regex = /abc/;
console.log(Object.prototype.toString.call(regex));  // 输出 "[object RegExp]"

let error = new Error();
console.log(Object.prototype.toString.call(error));  // 输出 "[object Error]"

let nullValue = null;
console.log(Object.prototype.toString.call(nullValue));  // 输出 "[object Null]"

let undefinedValue = undefined;
console.log(Object.prototype.toString.call(undefinedValue));  // 输出 "[object Undefined]"

5. 使用 typeof 与 null 的特殊判断

需要注意的是,typeof null 返回 "object",因为在 JavaScript 中将 null 错误地归类为对象。因此,如果要判断一个变量是否为 null,可以使用 === null 来做精确判断。

let nullValue = null;
console.log(typeof nullValue);  // 输出 "object"
console.log(nullValue === null);  // 输出 true

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值