JavaScript的typeof返回哪些数据类型
在 JavaScript 中,typeof
是一个用于检测变量或表达式类型的操作符。它返回一个表示数据类型的字符串。以下是 typeof
可能返回的结果:
"undefined"
- 表示变量未定义或未赋值。
javascript
let a;
console.log(typeof a); // "undefined"
console.log(typeof b); // "undefined"(未声明的变量)
"boolean"
- 表示布尔值(
true
或false
)。
vbnet
let isTrue = true;
console.log(typeof isTrue); // "boolean"
"number"
- 表示数字类型(包括整数、浮点数、
NaN
和Infinity
)。
ini
let num = 42;
let float = 3.14;
let nan = NaN;
let inf = Infinity;
console.log(typeof num); // "number"
console.log(typeof float); // "number"
console.log(typeof nan); // "number"(NaN 是数字类型)
console.log(typeof inf); // "number"
"string"
- 表示字符串类型。
ini
let str = "Hello, World!";
console.log(typeof str); // "string"
"bigint"
- 表示大整数类型(
BigInt
)。
ini
let bigNum = 123n;
console.log(typeof bigNum); // "bigint"
"symbol"
- 表示符号类型(
Symbol
)。
javascript
let sym = Symbol("foo");
console.log(typeof sym); // "symbol"
"object"
- 表示对象类型(包括普通对象、数组、
null
等)。
javascript
let obj = { name: "Alice" };
let arr = [1, 2, 3];
let nul = null;
console.log(typeof obj); // "object"
console.log(typeof arr); // "object"(数组也是对象)
console.log(typeof nul); // "object"(null 被错误地识别为对象,这是历史遗留问题)
"function"
- 表示函数类型。
javascript
function foo() {}
console.log(typeof foo); // "function"
"object"
(特殊对象)
- 对于内置对象(如
Date
、RegExp
、Map
、Set
等),typeof
也会返回"object"
。
javascript
console.log(typeof new Date()); // "object"
console.log(typeof /regex/); // "object"
console.log(typeof new Map()); // "object"
console.log(typeof new Set()); // "object"
总结
typeof
返回的可能值有:
"undefined"
"boolean"
"number"
"string"
"bigint"
"symbol"
"object"
"function"
需要注意的是,typeof null
返回 "object"
,这是 JavaScript 的一个历史遗留问题。如果需要更精确的类型判断,可以使用 Object.prototype.toString.call()
或 instanceof
。
更多vue相关插件及后台管理模板可访问vue admin reference,代码详情请访问github