类型检测
一、typeof
例子:
typeof 100 === "number"
typeof "字符串" === "string"
注意:typeof 适合基本类型(number、string、boolean、underfined、object)以及function检测,遇到null失效。
二、instanceof
例子:
["数组1","数组2"] instanceof Array === true;
注意: instanceof 适合自定义对象,也可以用来检测原生对象(Array、Date、RegExp、Function),在不同iframe和window间检测时失效。
三、Object.prototype.toString
例子:
Object.prototype.toString.apply([]) === "[object Array]";
Object.prototype.toString.apply(function(){}) === "[object Function]";
Object.prototype.toString.apply(null) === "[object Null]";
注意: 适合内置对象和基元类型,遇到null和undefined失效(IE678等返回[object Object])。

浙公网安备 33010602011771号