js typeof实现
typeof 的实现原理
JavaScript 中的 typeof 操作符用于检测变量的数据类型。其底层实现与 JavaScript 引擎的内部类型标签机制相关。具体原理如下:

- 在 JavaScript 引擎(如 V8)中,每个值都有一个隐藏的类型标签(通常是一个 1-3 位的二进制值)
typeof通过读取这个标签来判断类型- 对于对象类型(包括 null),标签为
0,而typeof null返回"object"是一个历史遗留的 bug
常见返回值
typeof 可能返回以下字符串:

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 123n // "bigint"
手动实现 typeof
可以通过 Object.prototype.toString 实现更精确的类型判断:
function typeOf(value) {
return Object.prototype.toString.call(value).slice(8, -1).toLowerCase()
}
typeOf(null) // "null"
typeOf([]) // "array"
typeOf({}) // "object"
typeOf(new Date) // "date"
注意事项
typeof对未声明的变量返回"undefined"而不会报错- 函数虽然是对象,但
typeof会特殊返回"function" - 数组和普通对象都会返回
"object",需要额外方法区分 - 在 ES6 中新增了对
Symbol和BigInt类型的支持






