JavaScript 中检测对象的六种方法:使用 typeof 运算符判断类型。使用 Array.isArray(obj) 检测数组。使用 obj instanceof Type 检测特定类型(布尔值、日期、函数、正则表达式)。使用 Array.isArray() 或 obj.constructor === Array 区分对象和数组。通过 Object.keys(obj).length === 0 判断空对象。通过 !Array.isArray(obj) && typeof o

如何使用 JavaScript 检测对象
直接检测
最直接的方法是使用 typeof 运算符:
<code class="js">const obj = { name: "John" };
console.log(typeof obj); // "object"</code>检测特定类型
JavaScript 中有六种内置的对象类型:
- 数组:
Array.isArray(obj) - 布尔值:
obj instanceof Boolean - 日期:
obj instanceof Date - 函数:
obj instanceof Function - Null:
obj === null - 正则表达式:
obj instanceof RegExp
例如:
<code class="js">console.log(Array.isArray([1, 2, 3])); // true console.log(obj instanceof Boolean); // false</code>
区分对象和数组
数组也是对象,但可以通过 Array.isArray() 函数或 obj.constructor === Array 来分辨。
<code class="js">console.log(Array.isArray({})); // false
console.log({}.constructor === Array); // false</code>检测空对象
如果对象没有属性,则可以通过以下方式检测:
<code class="js">const isEmpty = (obj) => Object.keys(obj).length === 0;
console.log(isEmpty({})); // true</code>检测哈希表
哈希表是键值对集合,可以通过以下方式检测:
<code class="js">const isHash = (obj) => !Array.isArray(obj) && typeof obj === "object";
console.log(isHash({ name: "John" })); // true</code>










