JS中类型判断

[TOC]
typeof
instanceof
hasOwnProperty

typeof

typeof只能区分下面的类型:
undefined
boolean
number
string
object:对象、null、数组
function:函数
typeof不适合用于判断是否为数组。当使用typeof判断数组和对象的时候,都会返回object。可以使用isArray()来判断是否为数组。

  • NaN(就是not a number啦)和infinity一样是number类型的一个特殊的值
  • typeof null===”object”

instanceof

instanceof 用于判断一个变量是否某个对象的实例。
instance只能用来判断对象和函数,不能用来判断字符串、数组等


constructor

返回对创建此对象的原始封装类对象。原始封装对象有:Object、Array、Boolean、Number、String、Function、Date、Math、RegExp、Arguments
如:str.constructor是String、array.constructor是Array


prototype(推荐)

Object.prototype.toString.call(对象)来判断对象类型

热评文章