Javascript教程
JavaScript基础
JavaScript Objects
JavaScript BOM
JavaScript DOM
JavaScript OOP
JavaScript Cookies
JavaScript事件
JavaScript异常
JavaScript常用

JavaScript typeof

JavaScript typeof 运算符用于返回一个字符串,该字符串代表给定值的JavaScript类型。它以字符串形式返回操作数的数据类型。操作数可以是文字或数据结构,例如函数,对象或变量。

语法

使用typeof有以下两种方法运算符。
typeof operand
or
typeof (operand)

操作数::它是表示要返回其类型的对象或基元的表达式。
typeof 运算符的可能返回值列表如下:
操作数的类型 结果
object "对象"
number "数字"
string "字符串"
boolean "布尔值"
function "功能"
undefined "未定义"
让我们通过一些示例来了解此运算符。

Example1

在此示例中,操作数是数字类型。 typeof 运算符将打印 "数字" 作为操作数的类型,无论操作数是负整数,浮点数,无穷大,NaN,零还是任何整数。
<html>
<head>
<script>
document.write(typeof (45) + "<br>"); // results: "number"
document.write(typeof (-90) + "<br>"); // results: "number"
document.write(typeof (0) + "<br>"); // results: "number"
document.write(typeof (22.6) + "<br>"); // results: "number"
document.write(typeof (Infinity) + "<br>"); // results: "number"
document.write(typeof (NaN)); // results: "number". Although NaN is "Not-A-Number"
</script>
</head>
<body>
</body>
</html>
输出

Example2

在此示例中,操作数为字符串类型。 typeof 运算符将打印 "字符串" 作为操作数的类型,无论操作数是空字符串,字符集合还是用引号引起来的数字。
<html>
<head>
<script>
document.write(typeof ("") + "<br>"); // results: "string"
document.write(typeof ("lidihuo.com") + "<br>"); // results: "string"
document.write(typeof ("20") + "<br>"); // results: "string"
document.write(typeof (typeof 1) + "<br>"); // results: "string"
document.write(typeof String(12)); // wrapping in String function will results: "string"
</script>
</head>
<body>
</body>
</html>
输出

Example3

在此示例中,操作数为布尔类型。如果操作数为 true false <, typeof 运算符将打印" boolean" 作为操作数的类型。
<html>
<head>
<script>
document.write(typeof (true) + "<br>"); // results: "boolean"
document.write(typeof (false) + "<br>"); // results: "boolean"
document.write(typeof Boolean(20) + "<br>"); // wrapping in Boolean function will results: "boolean"
</script>
</head>
<body>
</body>
</html>
输出

Example4

在此示例中,操作数是未定义的类型。 typeof 运算符将打印 "未定义" 作为操作数的类型。在这里, 的类型为 未定义,这是因为它被写为 而不是 。如果我们将其写为 null ,则其类型将为 object。
<html>
<head>
<script>
document.write(typeof Null + "<br>"); // results: "undefined"
document.write(typeof undefined + "<br>"); // results: "undefined"
document.write(typeof a + "<br>"); // results: "undefined"
</script>
</head>
<body>
</body>
</html>
输出

Example5

在此示例中,操作数为 Object Function 类型。 typeof 运算符将根据操作数的类型打印 "对象" "功能"
<html>
<head>
<script>
document.write(typeof null + "<br>"); // results: "object"
document.write(typeof [1, 2, 'hello'] + "<br>"); // results: "object"
document.write(typeof {a: 'hello'} + "<br>"); // results: "object"
document.write(typeof [1, 2, 3, 4] + "<br>"); // results: "object"
document.write(typeof function(){} + "<br>"); // results: "function"
document.write(typeof class hello{} + "<br>"); // results: "function"
</script>
</head>
<body>
</body>
</html>
输出
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4