一、typeof操作符的深层机制
typeof是JavaScript中的一元操作符,用于检测变量的数据类型。它返回一个表示类型的字符串,但存在一个历史遗留问题:
console.log(typeof 42); // "number"
console.log(typeof "hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (历史遗留bug)
console.log(typeof []); // "object"
console.log(typeof {}); // "object"
console.log(typeof function(){}); // "function"
二、null与undefined的本质区别
undefined表示变量已声明但未赋值,或函数未明确返回值时的默认返回值:
let unassigned;
console.log(unassigned); // undefined
function test() {}
console.log(test()); // undefined
null是一个明确赋值给变量的特殊值,表示"空值"或"无对象":
let emptyValue = null;
console.log(emptyValue); // null
三、相等性比较的陷阱
松散相等(==)和严格相等(===)对null和undefined的处理不同:
console.log(null == undefined); // true
console.log(null === undefined); // false
console.log(null == 0); // false
console.log(undefined == 0); // false
四、实战应用与精准检测
安全检测undefined:
if (typeof variable === 'undefined') {
// 安全地检测未定义变量
}
精准检测null:
if (variable === null) {
// 明确检测null值
}
综合类型检测方案:
function getType(value) {
if (value === null) return "null";
return typeof value;
}
五、总结
理解typeof、null和undefined的细微差别是掌握JavaScript类型系统的关键。typeof返回类型字符串但对null错误返回"object";undefined表示未定义状态;null则是明确的空值赋值。在实际开发中,建议始终使用严格相等(===)进行类型和值的比较,避免松散相等带来的隐式转换问题。

被折叠的 条评论
为什么被折叠?



