Appearance
普通对象检查 (isPlainObject)
检查值是否为普通对象(由 Object 构造函数创建或对象字面量创建的对象)。
签名
typescript
function isPlainObject(value: unknown): value is Record<string, unknown>;参数
value(unknown): 要检查的值。
返回值
(boolean) 如果值是普通对象返回 true,否则返回 false。
示例
typescript
import { isPlainObject } from '@fu/matrix';
// 或
const isPlainObject = window.fuMatrix.isPlainObject;
// 普通对象
isPlainObject({}); // => true
isPlainObject({ a: 1 }); // => true
isPlainObject(Object.create(null)); // => true
// 非普通对象
isPlainObject([]); // => false
isPlainObject(null); // => false
isPlainObject(undefined); // => false
isPlainObject(42); // => false
isPlainObject('string'); // => false
isPlainObject(new Date()); // => false
isPlainObject(new Map()); // => false
isPlainObject(new Set()); // => false
isPlainObject(() => {}); // => false
// 类实例
class TestClass {}
isPlainObject(new TestClass()); // => false普通对象判断规则
普通对象是指:
- 通过对象字面量
{}创建的对象 - 通过
Object()构造函数创建的对象 - 通过
Object.create(null)或Object.create(Object.prototype)创建的对象
以下不被视为普通对象:
- 数组
- 函数
null和undefined- 基本类型值(字符串、数字、布尔值等)
- 内置对象实例(如 Date、RegExp、Map、Set 等)
- 自定义类的实例
注意事项
- 该函数使用
Object.getPrototypeOf()检查对象的原型链 - 与
typeof value === 'object'不同,该函数更严格地识别普通对象 - 该函数是类型安全的,会进行类型保护