📜  javascript typeof - Javascript (1)

📅  最后修改于: 2023-12-03 14:42:27.733000             🧑  作者: Mango

JavaScript typeof

简介

在 JavaScript 中,typeof 是一个用于确定变量或表达式的数据类型的操作符。它返回一个字符串,指示给定对象的数据类型。

语法
typeof operand

typeof 后面跟着一个操作数,可以是变量、表达式或者字面量值。

返回值

typeof 操作符返回一个字符串,表示操作数的数据类型。常见的返回值有以下几种:

  • "undefined": 如果操作数是未定义的变量或者值。
  • "boolean": 如果操作数是布尔值。
  • "number": 如果操作数是数字。
  • "string": 如果操作数是字符串。
  • "symbol": 如果操作数是符号值。
  • "bigint": 如果操作数是大整数。
  • "object": 如果操作数是对象(除了函数和数组)或 null
  • "function": 如果操作数是函数。
  • "array": 如果操作数是数组。
示例

以下是一些使用 typeof 操作符的示例:

const undefinedVariable = undefined;
const booleanVariable = true;
const numberVariable = 42;
const stringVariable = "Hello, world!";
const symbolVariable = Symbol("symbol");
const bigintVariable = BigInt(1234567890);
const objectVariable = { key: "value" };
const functionVariable = function() { console.log("Function"); };
const arrayVariable = [1, 2, 3];

console.log(typeof undefinedVariable); // 输出 "undefined"
console.log(typeof booleanVariable); // 输出 "boolean"
console.log(typeof numberVariable); // 输出 "number"
console.log(typeof stringVariable); // 输出 "string"
console.log(typeof symbolVariable); // 输出 "symbol"
console.log(typeof bigintVariable); // 输出 "bigint"
console.log(typeof objectVariable); // 输出 "object"
console.log(typeof functionVariable); // 输出 "function"
console.log(typeof arrayVariable); // 输出 "object"

如上所示,typeof 操作符可以用来判断变量的数据类型。注意 typeof arrayVariable 返回的是 "object",这是因为在 JavaScript 中,数组被视为对象的一种特殊类型。

总结

typeof 是 JavaScript 中用于确定变量或表达式的数据类型的操作符。它返回一个字符串,表示操作数的类型。使用 typeof 可以方便地对变量进行类型判断和处理。