写函数判断变量的数据类型(JS原理)

  • 使用 typeof 操作符:typeof 是JavaScript的一个关键字,用于确定一个值的数据类型。它返回一个字符串,表示给定值的类型。
console.log(typeof 42);    // 输出:"number"
console.log(typeof "Hello");   // 输出:"string"
console.log(typeof true);   // 输出:"boolean"
console.log(typeof undefined);   // 输出:"undefined"
console.log(typeof null);   // 输出:"object" (注意此处的历史遗留问题)
console.log(typeof [1, 2, 3]);   // 输出:"object"
console.log(typeof { name: "John", age: 25 });   // 输出:"object"

需要注意的是,typeof null 返回 "object",这是JavaScript中的历史遗留问题。  


  • 使用 instanceof 操作符:instanceof 用于检查一个对象是否是某个特定类的实例

console.log([] instanceof Array);    // 输出:true
console.log({} instanceof Object);   // 输出:true
console.log(new Date() instanceof Date);   // 输出:true
console.log("Hello" instanceof String);    // 输出:false

 注意,一般是用来判断引用数据类型,但不能正确判断基本数据类型在对基本类型进行判断时,instanceof 会返回 false


  • 使用 Array.isArray() 函数:Array.isArray() 用于判断一个值是否为数组。  
console.log(Array.isArray([1, 2, 3]));    // 输出:true
console.log(Array.isArray({}));   // 输出:false

这个方法只能判断是否为数组,无法判断其他类型。


  •  使用 Object.prototype.toString.call() 方法:这个方法比较复杂,但可以准确地判断绝大多数数据类型,包括基本类型和对象。
console.log(Object.prototype.toString.call(42));    // 输出:"[object Number]"
console.log(Object.prototype.toString.call("Hello"));   // 输出:"[object String]"
console.log(Object.prototype.toString.call(true));   // 输出:"[object Boolean]"
console.log(Object.prototype.toString.call(undefined));   // 输出:"[object Undefined]"
console.log(Object.prototype.toString.call(null));   // 输出:"[object Null]"
console.log(Object.prototype.toString.call([1, 2, 3]));   // 输出:"[object Array]"
console.log(Object.prototype.toString.call({ name: "John", age: 25 }));   // 输出:"[object Object]"

 这种方法使用 call() 方法将 Object.prototype.toString() 方法应用到要检查的值上。返回的字符串形式 [object 类型] 可以准确表示数据类型。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值