js中数据类型的判断方式

1.typeof方法判断数据类型,一般用于基本数据类型的判断,不适用引用数据类型,另外对于null,object、array返回的都是object,无法进行区分。

console.log(typeof null);//object
console.log(typeof {name:"小明"})//object
console.log(typeof [1,3,5,6]);//object
console.log(typeof undefined);//undefined
console.log(typeof 1);//number
console.log(typeof "1");//string
console.log(typeof Symbol);//function
console.log(typeof function(){});//function
console.log(typeof true);//boolean

2.instanceof方法 是用来 判断数据是否是某个对象的实例,返回一个布尔值。对于基本类型的数据,instanceof是不能直接判断它的类型的,因为实例是一个对象或函数创建的,是引用类型,所以需要通过基本类型对应的包装对象来判断。所以对于 null 和 undefined无法检测。

// 判断 p 是否为 Person 的实例
function Person(name) {
  this.name = name
}
const p = new Person('sunshine')
console.log(p instanceof Person); // true
 
// 这里的 p 是 Person 函数构造出来的,所以顺着 p 的原型链可以找到Object的构造函数
console.log(p.__proto__ === Person.prototype); // true
console.log(p.__proto__.__proto__ === Object.prototype); // true
console.log(5 instanceof Number); // false
console.log(new Number(5) instanceof Number);  // true

3.Object.prototype.toString.call()方法,这种方式判断数据类型是最准确的。

console.log(Object.prototype.toString.call(null));//[object Null]
console.log(Object.prototype.toString.call({name:"小明"}))//[object Object]
console.log(Object.prototype.toString.call([1,3,5,6]));//[object Array]
console.log(Object.prototype.toString.call(undefined));//[object Undefined]
console.log(Object.prototype.toString.call(1));//[object Number]
console.log(Object.prototype.toString.call("1"));//[object String]
console.log(Object.prototype.toString.call(Symbol));//[object Function]
console.log(Object.prototype.toString.call(function(){}));//[object Function]
console.log(Object.prototype.toString.call(true));//[object Boolean]

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

爱在 旅途

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

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

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

打赏作者

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

抵扣说明:

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

余额充值