js判断数据类型的方法

js判断数据类型的方法

typeof 判断数据类型

JavaScript 中使用 typeof 判断数据类型,只能区分基本类型(number、string、boolean、undefined、function、object),如果数据类型为 null、array、object ,使用 typeof 判断都会统一返回 ‘’object‘’ 字符串

console.log(typeof(1))   //number
console.log(typeof('a'))   //string
console.log(typeof(true))   //boolean
console.log(typeof(undefined))   //undefined
console.log(typeof(function({}))   //function
console.log(typeof(null))   //object
console.log(typeof([1,2,3]))   //object
console.log(typeof({a'b'}))   //object

instanceof 判断数据类型

instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上

  • 判断一个数据是否为某个对象的实例
function Father({}
let son = new Father()
console.log(son instanceof Father)   //true
  • 判断一个数据是否为某个引用类型
console.log(function({} instanceof Function)   //true
console.log([1,2,3instanceof Array)   //true
console.log({a'b'instanceof Object)   //true

constructor 判断数据类型

constructor 是原型对象上的属性,指向构造函数,可以通过 constructor 来判断数据的类型

注:null、undefined 没有 constructor 属性,不能用来判断
let num = 1
console.log(num.constructor == Number)   //true
let str = 'a'
console.log(str.constructor == String)   //true
let bool = true
console.log(bool.constructor == Boolean)   //true
let fn = function({}
console.log(fn.constructor == Function)   //true
let ary = [1,2,3]
console.log(ary.constructor == Array)   //true
let obj = {a'b'}
console.log(obj.constructor == Object)   //true

Object.prototype.toString.call() 判断数据类型

默认情况下,toString() 方法被每个 Object 对象继承,如果此方法在自定义对象中未被覆盖, toString() 方法会返回一个 “[object xxxx]” 的字符串(xxxx 为数据具体类型)。可以通过 toString() 来获取每个对象的类型,为了每个对象都能通过 Object.prototype.toString() 来检测,需要以 call() 或者 apply() 的形式来调用,传递要检查的对象作为第一个参数,即 Object.prototype.toString.call()(或者 Object.prototype.toString.apply())

console.log(Object.prototype.toString.call(1))   //[object Number]
console.log(Object.prototype.toString.call('a'))   //[object String]
console.log(Object.prototype.toString.call(true))   //[object Boolean]
console.log(Object.prototype.toString.call(undefined))   //[object Undefined]
console.log(Object.prototype.toString.call(function({}))   //[object Function]
console.log(Object.prototype.toString.call(null))   //[object Null]
console.log(Object.prototype.toString.call([1,2,3]))   //[object Array]
console.log(Object.prototype.toString.call({a'b'}))   //[object Object]


原文始发于微信公众号(前端24):js判断数据类型的方法

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/217062.html

(0)
李, 若俞的头像李, 若俞

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!