实现说明
typeof 与 Array.isArray 组合类型检查可以归结为函数 isPlainObject。
这个示例中仅有的重复出现在 for (const [label, value] of samples) 里。
使用要点
- 跑完文件,输出里会留下标记——
typeof null is、isPlainObject passes for:。
常见问题
运行之前需要装什么吗?
不需要——用到的每个 API 都随语言运行时自带,无需安装。 文件在加载时定义 isPlainObject。
主要签名是 function isPlainObject(value)
核心语句
const passed = samples.filter(([, v]) => isPlainObject(v)).map(([label]) => label);
return typeof value === 'object' && value !== null && !Array.isArray(value);
代码示例
// Runtime type checks for values that come back from JSON payloads
const samples = [
['null', null],
['undefined', undefined],
['number', 42],
['NaN', NaN],
['string', 'text'],
['boolean', true],
['array', []],
['object', {}],
['function', () => {}],
['bigint', 10n],
];
for (const [label, value] of samples) {
const kind = value === null ? 'null' : typeof value;
console.log(label.padEnd(10), 'typeof =', kind.padEnd(10), 'Array.isArray =', Array.isArray(value));
}
// typeof null 报告 'object' 是历史遗留:先挡空值,再用 Array.isArray 区分数组
function isPlainObject(value) {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
console.log('typeof null is', typeof null, '- the guard above rejects it first');
const passed = samples.filter(([, v]) => isPlainObject(v)).map(([label]) => label);
console.log('isPlainObject passes for:', passed.join(', '));