JavaScript 中的 typeof 运算符是什么?

javascriptweb developmentfront end technology

typeof 运算符是一个一元运算符,位于其单个操作数之前,该操作数可以是任何类型。其值是一个字符串,表示操作数的数据类型。如果 typeof 运算符的操作数是数字、字符串或布尔值,则该运算符的计算结果为"number"、"string"或"boolean",并根据计算结果返回 true 或 false。

以下是 typeof 运算符的返回值列表。

Type
String Returned by typeof
Number
"number"
String
"string"
Boolean
"boolean"
object
"object"
Function
"function"
Undefined
"undefined"
Null
"object"

示例

以下代码显示如何实现 typeof 运算符 −

<html>
   <body>
      <script>
         var a = 10;
         var b = "String";
         var linebreak = "<br />";

         result = (typeof b == "string" ? "B is String" : "Bis Numeric");
         document.write("Result => ");
         document.write(result);
         document.write(linebreak);

         result = (typeof a == "string" ? "A is String" : "Ais Numeric");
         document.write("Result => ");
         document.write(result);
         document.write(linebreak);
      </script>
   </body>
</html>

相关文章


有用资源