- List item
数据类型判断
- typeof
typeof 666, // Number,
typeof 'abc', // String,
typeof true ,// Bolearn,
typeof {} , // object,
typeof [] , // object,
typeof null , // object ,
typeof undefined, //undefined
typeof /^[a-zA-Z]{5,20}$/ // object
typeof new Date() , //object
typeof function(){} ,//function
基本数据类型中:null 。引用数据类型中的:Array,Object,Date,RegExp。不可以用typeof检测。都会返回object
- instanceof
100 instanceof Number, //false
'abc' instanceof String, //false
true instanceof Boolean,//false
// null instanceof Null, // 报错
// undefined instanceof Undefined, // 报错
{} instanceof Object,//true
[] instanceof Array,//true
new Date() instanceof Date,//true
/666/ instanceof RegExp,//true
function(){} instanceof Function ,//true
也就是instanceof 可以检测引用数据类型 但不能检测基本数据类型 并且检测 null和undefined的时候还会报错
- constructor 属性返回对创建此对象的 Date 函数的引用。
var arr = [1, 2]
var nub = 1123
var obj = {}
var und = undefined
var nul = null
var str = 'abc'
var reg = /^[a-zA-Z]{5,20}$/
// undefined和null没有constructor属性
consol.log(
arr.constructor == Array,
nub.constructor == Number,
obj.constructor == Object,
// und.constructor==Undefined, //报错
// null.constructor==Null, // 报错
str.constructor == String,
reg.constructor == RegExp,
)
也就是null和undefined不能用此方法检测
- 使用Object.prototype.toString.call()检测对象类型
var nb=Object.prototype.toString
nu.call(123)// [object Number]
nu.call([1,2])// [object Array]
nu.call({a:1})// [object Object]
nu.call(/^[a-zA-Z]{5,20}$/)// [object RegExp]
nu.call(asd)// [object String]
这个还是可行的
- jquery.type()
jquery.type(123) // number
jquery.type([1,2]) // array
jquery.type({a:1}) // object
jquery.type(abc) // string
本文介绍了JavaScript中数据类型的判断方法,包括使用typeof、instanceof及constructor属性等,并对比了各自的适用场景与限制。

被折叠的 条评论
为什么被折叠?



