typeof
运算符返回变量和值的类型。例如,
const a = 9;
console.log(typeof a); // number
console.log(typeof '9'); // string
console.log(typeof false); // boolean
typeof 运算符的语法
typeof
运算符的语法是:
typeof operand
这里,operand 是变量名或值。
typeof 的类型
typeof
运算符在 JavaScript 中可以返回的可能类型有:
类型 | typeof 结果 |
---|---|
字符串 |
"string" |
Number |
"number" |
BigInt |
"bigint" |
布尔型 |
"boolean" |
对象 |
"object" |
Symbol |
"symbol" |
undefined |
"undefined" |
null |
"object" |
function | "function" |
示例 1:字符串的 typeof
const str1 = 'Peter';
console.log(typeof str1); // string
const str2 = '3';
console.log(typeof str2); // string
const str3 = 'true';
console.log(typeof str3); // string
示例 2:数字的 typeof
const number1 = 3;
console.log(typeof number1); // number
const number2 = 3.433;
console.log(typeof number2); // number
const number3 = 3e5
console.log(typeof number3); // number
const number4 = 3/0;
console.log(typeof number4); // number
示例 3:BigInt 的 typeof
const bigInt1 = 900719925124740998n;
console.log(typeof bigInt1); // bigint
const bigInt2 = 1n;
console.log(typeof bigInt2); // bigint
示例 4:布尔值的 typeof
const boolean1 = true;
console.log(typeof boolean1); // boolean
const boolean2 = false;
console.log(typeof boolean2); // boolean
示例 5:Undefined 的 typeof
let variableName1;
console.log(typeof variableName1); // undefined
let variableName2 = undefined;
console.log(typeof variableName2); // undefined
示例 6:null 的 typeof
const name = null;
console.log(typeof name); // object
console.log(typeof null); // object
示例 7:Symbol 的 typeof
const symbol1 = Symbol();
console.log(typeof symbol1); // symbol
const symbol2 = Symbol('hello');
console.log(typeof symbol2); // symbol
示例 8:Object 的 typeof
let obj1 = {};
console.log(typeof obj1); // object
let obj2 = new String();
console.log(typeof obj2); // object
let obj3 = [1, 3, 5, 8];
console.log(typeof obj3); // object
示例 9:Function 的 typeof
let func = function () {};
console.log(typeof func); // function
// constructor function
console.log(typeof String); // function
console.log(typeof Number); // function
console.log(typeof Boolean); // function
typeof 运算符的用途
typeof
运算符可用于在特定时间点检查变量的类型。例如,
let count = 4;
console.log(typeof count);
count = true;
console.log(typeof count);
- 您可以为不同类型的数据执行不同的操作。例如,
let count = 4;
if(typeof count === 'number') {
// perform some action
}
else if (typeof count = 'boolean') {
// perform another action
}