0
点赞
收藏
分享

微信扫一扫

js判断数据类型的方法

Raow1 2022-03-25 阅读 71

1.typeof

对于基本数据类型可以直接判断

  • typeof  1  number
  • typeof  "1"  string

对于复合类型,除了函数,其他返回Object

  • typeof {}  Object

  • typeof [ ]  Object

  • typeof function(){}  Function

对于null和undefined Boolean

  • typeof null  Object

  • typeof undefined  undefined

  • typeof true  Boolean

2.constructor 每个原形都会有的属性,指向关联的原形对象

  • "".constructor==String
  • [].constructor==Array
  • {}.constructor==Object
  • new Function().constructor==Function
  • let num=123  num.constructor==Number

  • let num=true  num.constructor==Boolean

  • 1.null和undefined是无效的对象,因此是不会有constructor存在的
    2.JS对象的constructor主要体现在自定义对象上,当开发者重写prototype后,原有的constructor会丢失,constructor会默认为Object

3.Object.prototype.toString.call()

Object.prototype.toString.call(’’) ; // [object String]
Object.prototype.toString.call(1) ; // [object Number]
Object.prototype.toString.call(true) ; // [object Boolean]
Object.prototype.toString.call(undefined) ; // [object Undefined]
Object.prototype.toString.call(null) ; // [object Null]
Object.prototype.toString.call(new Function()) ; // [object Function]
Object.prototype.toString.call([]) ; // [object Array]

4.转换为true和false的数据类型 

转换为true的数据类型转换为false的数据类型
booleantruefalse
number任何非零的数值
string非空字符串空字符串
object任何对象null
undefinedundefined

 

举报

相关推荐

0 条评论