内置类型
- 空值 null
- 未定义 undefined
- 布尔值 boolean
- 数字 Number
- 字符串 String
- 对象 Object
- 符号 symbol
typeof
typeof操作符返回一个字符串,表示未经计算的操作数的类型。
typeof operandtypeof(operand)typeof undefined === 'undefined'typeof undeclared === 'undefined'typeof true === 'boolean'typeof 22 === 'number'typeof NaN === 'number'typeof '22' === 'string'typeof [] === 'object'typeof {} === 'object'typeof null === 'object'typeof /regex/ === 'object'typeof new Date() === 'object'typeof new String() === 'object'...typeof new Function() === 'function'typeof function a(){} === 'function'
除了Function之外的所有构造函数的类型都是’object’。
undefined是值的一种,为未定义,而undeclared则表示变量还没有被声明过。在我们试图访问一个undeclared变量时会这样报错:‘ReferenceError:a is not defined。通过typeof对undefined和undeclared变量都返回”undefined”
注意:变量没有类型,只有值才有。类型定义了值的行为和特征。
instanceof
instanceof运算数是用于检测contructor.prototype属性是否出现在某个实例对象的原型链上。
object instanceof constructor22 instanceof Number => false'22' instanceof String => false[] instanceof Object => true{} instanceof Object => trueundefined instanceof Object => falsenull instanceof Object => falsenull instanceof null => Uncaught TypeError: Right-hand side of 'instanceof' is not an objectnew String('22') instanceof String => truenew Number(22) instanceof Number => true
instanceOf的主要实现原理就是只要右边变量的prototype在左边变量的原型链上即可。因此,instanceof在查找过程中会遍历左边变量的原型链,知道找到右边变量的prototype,如果查找失败就会返回false。
Object.prototype.toString.call()
Object.prototype.toString.call(22) => "[object Number]"Object.prototype.toString.call('22') => "[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(Math) => "[object Math]"Object.prototype.toString.call(new Date) => "[object Date]"Object.prototype.toString.call(Symbol(22))=> "[object Symbol]"Object.prototype.toString.call(() => {}) => "[object Function]"Object.prototype.toString.call(null) => "[object Null]"Object.prototype.toString.call(undefined) => "[object Undefined]"
类型判断
用 typeof 来判断变量类型的时候,我们需要注意,最好是用 typeof 来判断基本数据类型(包括symbol),避免对 null 的判断。不过需要注意当用typeof来判断null类型时的问题,如果想要判断一个对象的具体类型可以考虑使用instanceof,但是很多时候它的判断有写不准确。所以当我们在要准确的判断对象实例的类型时,可以使用Object.prototype.toString.call()进行判断。因为Object.prototype.toString.call()是引擎内部的方式。
