js基础与进阶--判断数据类型的四种方法

本文介绍了JavaScript中判断数据类型的四种方法:1)使用typeof操作符,2)使用instanceof检查原型链,3)通过constructor属性,4)利用Object.prototype.toString.call()。每种方法的使用场景和示例代码均有详细说明。
摘要由CSDN通过智能技术生成

js基础与进阶–判断数据类型的四种方法

1.常用typeof

2.instanceof

3.constructor方法

4.Object.prototype.toString.call()

1.type of

alert(typeof “helloworld”) ------------------>“string”
alert(typeof ‘undefined’) ------------------>“string”
alert(typeof 123) ------------------>“number”
alert(typeof null) ------------------>“object”
alert(typeof [1,2,3]) ------------------>“object”
alert(typeof new RegExp()) ------------------>“object”
alert(typeof new Date()) ------------------>“object”
alert(typeof Symbol()) ------------------>“function”
alert(typeof new Function()) ------------------>“function”
alert(typeof true) ------------------>‘boolean’
alert(typeof undefined) ------------------>“undefined”
基本数据类型里面:number–》number
boolean–》boolean
string–》string
null–》object
undefined–》undefined
引用数据类型大部分是object除了函数类是function

2instanceof

实例我就不全列举了
let arr1=[1,2,3,4,5]
arr1 instanceof Array
这里判断的原理是查找 构造函数的原型是否在arr1的原型链上面

3constructor方法

众所周知,构造函数,构造函数的原型,实例,三足鼎立
实例的construor和构造函数原型的constrcutor都是构造函数。
我们值需要判断arr1.constructor===Array

4Object.prototype.toString.call()

原理:由于担心函数的原型被重写,所以创建时候用的是Object的方法。
console.log(Object.prototype.toString.call(“123”)) -------->[object String]
console.log(Object.prototype.toString.call(123)) -------->[object Number]
console.log(Object.prototype.toString.call(true)) -------->[object Boolean]
console.log(Object.prototype.toString.call([1, 2, 3])) -------->[object Array]
console.log(Object.prototype.toString.call(null)) -------->[object Null]
console.log(Object.prototype.toString.call(undefined)) -------->[object Undefined]
console.log(Object.prototype.toString.call({name: ‘Hello’})) -------->[object Object]
console.log(Object.prototype.toString.call(function () {})) -------->[object Function]
console.log(Object.prototype.toString.call(new Date())) -------->[object Date]
console.log(Object.prototype.toString.call(/\d/)) -------->[object RegExp]
console.log(Object.prototype.toString.call(Symbol())) -------->[object Symbol]

祝各位一切顺利,创作不易,有帮助的话点个赞哦

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值