- typeof判断
typeof返回的类型都是字符串形式
alert(typeof "helloworld") // "string"
alert(typeof 123) // "number"
alert(typeof new Function()) // "function"
alert(typeof Symbol()) // "symbol"
alert(typeof true) // "true"
alert(typeof undefined) // "undefined"
alert(typeof 'undefined') // "string"
alert(typeof null) // "object"
alert(typeof [1,2,3]) // "object"
alert(typeof new Date()) // "object"
alert(typeof new RegExp()) // "object"
-
Constructor
实例constructor属性指向构造函数本身
constructor 判断方法跟instanceof相似,但是constructor检测Object与instanceof不一样,constructor还可以处理基本数据类型的检测,不仅仅是对象类型 -
Instanceof
instanceof可以判类型是否是实例的构造函数
instanceof 后面一定要是对象类型,并且大小写不能错,该方法适合一些条件选择或分支。
[1,2,3] instanceof Array // true
new Date() instanceof Date // true
new Function() instanceof Function // true
new Function() instanceof function // false
null instanceof Object // false
- Object.prototype.toString.call()
判断类型的原型对象是否在某个对象的原型链上
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]
-
通过object原型上的方法判断
比如array.isArray()来判断是不是一个数组 -
===(严格运算符)
通常出现在我们的条件判断中,用来判断数据类型的话就会非常的有局限性,比如判断一个变量是否为空,变量是否为数据等
二、typeof与instanceof区别
- typeof会返回一个变量的基本类型,instanceof返回的是一个布尔值
- instanceof 可以准确地判断复杂引用数据类型,但是不能正确判断基础数据类型
- 而typeof 也存在弊端,它虽然可以判断基础数据类型(null 除外),但是引用数据类型中,除了function 类型以外,其他的也无法判断