typeof在js中的含义

原创
ithorizon 6个月前 (10-19) 阅读数 69 #Javascript
typeof 运算符用于确定 javascript 中的变量或表达式的类型,并返回以下字符串值之一:"undefined": 变量未定义或值为 undefined"boolean": 变量为布尔值"number": 变量为数字"string": 变量为字符串"object": 变量为对象"function": 变量为函数"symbol": 变量为 symbol 类型(es6)"bigint": 变量为 bigint 类型(es2020)

typeof 在 JavaScript 中的含义

在 JavaScript 中,typeof 运算符用于确定一个变量或表达式的类型。它返回一个字符串,表示变量或表达式的类型。

用法:

typeof variable_or_expression;

其中,variable_or_expression 可以是任何有效的 JavaScript 变量或表达式。

可能的返回值:

typeof 运算符可以返回以下字符串值:

  • "undefined" - 当变量未定义或值为 undefined 时。
  • "boolean" - 当变量为布尔值(true 或 false)时。
  • "number" - 当变量为数字时。
  • "string" - 当变量为字符串时。
  • "object" - 当变量为对象时。
  • "function" - 当变量为函数时。
  • "symbol" - 当变量为 Symbol 类型时(ES6 中引入)。
  • "bigint" - 当变量为 BigInt 类型时(ES2020 中引入)。

示例:

console.log(typeof undefined); // "undefined"
console.log(typeof true); // "boolean"
console.log(typeof 42); // "number"
console.log(typeof "hello world"); // "string"
console.log(typeof {}); // "object"
console.log(typeof function() {}); // "function"
console.log(typeof Symbol()); // "symbol"
console.log(typeof 123n); // "bigint"

typeof 运算符可用于检查变量的类型,并根据类型执行不同的操作。例如,以下代码块检查变量 x 是否为数字,如果是数字,则将 x 加 1:

const x = 42;

if (typeof x === "number") {
  x++;
}

console.log(x); // 43

以上就是typeof在js中的含义的详细内容,更多请关注IT视界其它相关文章!



热门