最常用的方法,但有一些局限性:
typeof 42; // "number"
typeof "hello"; // "string"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object" (历史遗留问题)
typeof {}; // "object"
typeof []; // "object" (无法区分数组)
typeof function(){}; // "function"
typeof Symbol(); // "symbol"
typeof 42n; // "bigint"
特点:
检查对象是否属于特定类的实例:
[] instanceof Array; // true
{} instanceof Object; // true
new Date() instanceof Date; // true
function Person() {}
const p = new Person();
p instanceof Person; // true
// 局限性
"hello" instanceof String; // false(原始类型)
new String("hello") instanceof String; // true
最准确的方法,可以区分所有内置类型:
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(function(){});// "[object Function]"
Object.prototype.toString.call(/regex/); // "[object RegExp]"
Object.prototype.toString.call(new Date()); // "[object Date]"
专门判断数组:
Array.isArray([]); // true
Array.isArray({}); // false
Array.isArray("array"); // false
检查对象的构造函数:
[].constructor === Array; // true
{}.constructor === Object; // true
"".constructor === String; // true
// 注意:constructor 可被修改
const arr = [];
arr.constructor = Object;
arr.constructor === Array; // false
判断是否为 NaN:
Number.isNaN(NaN); // true
Number.isNaN("NaN"); // false
isNaN("NaN"); // true(会先转换)
// 判断是否为 null 或 undefined
function isNil(value) {
return value == null; // == 可以匹配 null 和 undefined
}
// 判断是否为纯对象(非数组、函数等)
function isPlainObject(obj) {
return Object.prototype.toString.call(obj) === "[object Object]";
}
// 判断是否为数字(包括数值字符串)
function isNumeric(value) {
return !isNaN(parseFloat(value)) && isFinite(value);
}
function getType(value) {
// 处理 null 和 undefined
if (value === null) return "null";
if (value === undefined) return "undefined";
const type = typeof value;
// 处理对象类型
if (type === "object" || type === "function") {
const toString = Object.prototype.toString.call(value);
return toString.slice(8, -1).toLowerCase();
}
return type;
}
// 使用示例
getType([]); // "array"
getType(null); // "null"
getType(new Map()); // "map"
getType(42n); // "bigint"
| 方法 | 优点 | 缺点 |
|---|---|---|
typeof |
简单快速,适合原始类型 | 无法区分对象类型 |
instanceof |
适合检查自定义类实例 | 不适用于原始类型,跨窗口问题 |
toString.call() |
最准确,支持所有类型 | 语法较长 |
Array.isArray() |
数组检测最佳实践 | 仅用于数组 |
constructor |
直接访问构造函数 | 可被修改,不安全 |
typeof
数组:使用 Array.isArray()
精确类型判断:使用 Object.prototype.toString.call()
自定义类实例:使用 instanceof
null/undefined:使用 value == null 或严格比较
选择哪种方法取决于具体场景,通常组合使用以达到最佳效果。