typeof 运算符
最基础的类型判断方式:
typeof 42; // "number" typeof "hello"; // "string" typeof true; // "boolean" typeof undefined; // "undefined" typeof null; // "object" (历史遗留问题) typeof []; // "object" typeof {}; // "object" typeof function(){}; // "function"
缺点:
无法区分数组和普通对象(都返回 "object")
null 也被识别为 "object"
2. instanceof 运算符
检测对象是否属于特定构造函数的实例:
[] instanceof Array; // true new Date() instanceof Date; // true function(){} instanceof Function; // true
缺点:
只能用于对象类型
跨窗口/iframe 使用时不可靠
3. Object.prototype.toString.call()
最准确的全类型判断方法:
Object.prototype.toString.call(42); // "[object Number]" Object.prototype.toString.call("hello"); // "[object String]" Object.prototype.toString.call(true); // "[object Boolean]" Object.prototype.toString.call(null); // "[object Null]" Object.prototype.toString.call(undefined);// "[object Undefined]" Object.prototype.toString.call([]); // "[object Array]" Object.prototype.toString.call({}); // "[object Object]" Object.prototype.toString.call(new Date());// "[object Date]"
4. Array.isArray()
专门判断数组类型(ES5+):
Array.isArray([]); // true Array.isArray({}); // false
5. 其他专门方法
// 判断NaN Number.isNaN(value); // 或 Object.is(value, NaN); // 判断整数 Number.isInteger(value); // 判断有限数 Number.isFinite(value);
6. 自定义类型判断函数
实现一个更完整的类型判断:
function getType(obj) { return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase(); } getType(42); // "number" getType(null); // "null" getType([]); // "array" getType(/regex/); // "regexp"
最佳实践建议
基本类型检查用 typeof
检查数组用 Array.isArray()
需要精确判断所有类型时用 Object.prototype.toString.call()
检查自定义对象实例用 instanceof(注意跨窗口问题)