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]
祝各位一切顺利,创作不易,有帮助的话点个赞哦