美文网首页
判断js类型的方法

判断js类型的方法

作者: 沉默紀哖呮肯伱酔 | 来源:发表于2021-03-25 11:41 被阅读0次

1、typeof

typeof 8 // number
typeof 'str' // string
typeof {} // object
typeof [] // object
typeof undefined // undefined
typeof true // boolean
typeof null // object
typeof function(){} // function

根据以上结果,我们可以看出typeof并不能精准的判断出复杂数据类型的类型,只能判断出基本类型数据

2、instanceof

[1,2] instanceof Array // true
{} instanceof Object // true

instanceof 只能判断复杂数据类型的真实类型

3、Object.prototype.toString.call()

通过原型链的方式找到数据的真实类型

Object.prototype.toString.call(9) // [object Number]
Object.prototype.toString.call('') // [object String]
Object.prototype.toString.call({}) // [object Object]
Object.prototype.toString.call([]) // [object Array]
Object.prototype.toString.call(true) // [object Boolean]
Object.prototype.toString.call(function(){}) // [object Function]
Object.prototype.toString.call(null) // [object Null]
Object.prototype.toString.call(undefined) // [object Undefined]

相关文章

网友评论

      本文标题:判断js类型的方法

      本文链接:https://www.haomeiwen.com/subject/idplhltx.html