typeof操作符在JavaScript中用于检测变量的数据类型,它能识别的基本类型包括:1.”number”、2.”String”、3.”Boolean”、4.”undefined”、5.”Object”(含NULL)、6.”function”、7.”symbol”、8.”bigint”;但需要注意typeof null返回”object”是历史问题,并不代表null是对象;判断数组应使用Array.isarray(),更复杂的对象类型建议用object.prototype.tostring.call()来判断。
在JavaScript中,typeof 是一个常用的操作符,用来检测变量的数据类型。它能识别一些基本数据类型,但也有局限性。下面我们就来看看它的使用方法和适用范围。
typeof 能检测哪些类型?
typeof 主要用于判断 JavaScript 中的基本数据类型,包括以下几种:
- “number”:数字类型,如 42 或 3.14
- “string”:字符串类型,如 “hello”
- “boolean”:布尔值,如 true 或 false
- “undefined”:未定义的变量
- “object”:对象类型(注意:null 也会返回 “object”)
- “function”:函数
- “symbol”:es6 引入的 Symbol 类型
- “bigint”:ES2020 新增的大整数类型
需要注意的是,typeof null 返回的是 “object”,这是一个历史遗留问题,并不代表 null 就是对象。
常见用法与建议
使用 typeof 非常简单,只需要在操作符后面加上一个变量或值即可:
console.log(typeof 123); // "number" console.log(typeof 'abc'); // "string" console.log(typeof true); // "boolean" console.log(typeof undefined); // "undefined" console.log(typeof { }); // "object" console.log(typeof function(){}); // "function" console.log(typeof Symbol()); // "symbol" console.log(typeof 9007199254740991n); // "bigint"
有几个使用时要注意的点:
- 判断是否为数组时不能依赖 typeof,因为它会返回 “object”,应该使用 Array.isArray()。
- 检查 null 时要单独处理,因为 typeof null === “object”。
- 对于基本类型来说,typeof 很好用;但对复杂结构(比如数组、日期等)就不够用了。
使用场景举例
-
调试时快速查看变量类型
console.log(typeof userInput);
这样可以快速知道用户输入的是字符串还是数字。
-
防止程序出错 在调用某个函数前检查参数是不是函数:
if (typeof callback === 'function') { callback(); }
-
处理不同类型的输入逻辑
function processInput(value) { if (typeof value === 'number') { console.log('你输入了一个数字'); } else if (typeof value === 'string') { console.log('你输入了一个字符串'); } }
不过,如果需要更精确地判断对象类型(例如判断是否为 date、regexp 等),建议使用 Object.prototype.toString.call()。
基本上就这些了。typeof 不复杂但容易忽略细节,尤其在处理 null 和数组时要特别小心。