W3CAPI 在线教程 | 菜鸟教程_LOGO
文档目录
文档目录
我的书签
 

JavaScript

JavaScript 入门教程

JavaScript是一门Web编程语言,用来实现网页的交互功能,它和HTML、CSS共同组成了个Web开发的基础工具集合,也是前端开发者必备的技能;学习JavaScript教程可以了解它在网页开发中的所有特性和相关概念,让我们能够更加快速的去开发Web应用。

W3CAPI
1
2020-06-18 07:05:48

typeof

JavaScript:typeof 运算符

JavaScript 类型检查

typeof 操作符用于获取其操作数的数据类型(返回字符串形式)。操作数可以是字面量或数据结构,例如变量、函数或对象。该操作符返回数据类型。

Syntax

typeof operand
or
typeof (operand)
执行一下

typeof 运算符返回的可能值共有六种:对象、布尔值、函数、数值、字符串和未定义。下表总结了 typeof 运算符可能返回的值。

操作数的类型Result
Object"object"
boolean"boolean"
function"function"
number"number"
string"string"
undefined"undefined"

typeof 运算符示例:字符串

Console

> typeof ""
"string"
> typeof "abc"
"string"
> typeof (typeof 1)
"string"
执行一下

typeof 运算符示例:number

Console

> typeof 17
"number"
> typeof -14.56
"number"
> typeof 4E-3
"number"
> typeof Infinity
"number"
> typeof Math.LN2
"number"
> typeof NaN
"number"
执行一下

typeof 操作符示例:boolean

Console

> typeof false
"boolean"
> typeof true
"boolean"
执行一下

typeof 运算符示例:function

Console

> typeof Math.tan
"function"
>typeof function(){}
"function"
执行一下

typeof 运算符示例:object

Console

> typeof {a:1}
"object"
> typeof new Date()
"object"
> typeof null
"object"
> typeof /a-z/
"object"
> typeof Math
"object"
> typeof JSON
"object"
执行一下

typeof运算符示例:undefined

Console

> typeof undefined
"undefined"
> typeof abc
"undefined"
执行一下

有关 typeof 运算符的更多示例

typeof(4+7);  //returns number
typeof("4"+"7"); //returns string
typeof(4*"7"); //returns number
typeof(4+"7"); //returns string
执行一下

JavaScript 中 typeof myvar 与 typeof(myvar) 的区别是什么?两者功能完全一致,括号仅用于包裹表达式,typeof 是操作符而非函数调用,语法允许但无行为差异。

两者之间绝对没有区别typeof myvar 的类型andtypeof(myvar)。如下代码的输出结果相同,即"undefined"。

alert(typeof myvar);

执行一下
alert(typeof(myvar));

执行一下

如何在 JavaScript 中检测对象属性是否为未定义?

以下方法是在JavaScript中检测对象属性是否为未定义的最佳方式。

if (typeof xyz === "undefined")
     alert("xyz is undefined");
执行一下

如何检测JavaScript变量是否已定义?使用typeof操作符检查是否为undefined,或通过try/catch块捕捉未声明变量的ReferenceError错误。

以下方法是在JavaScript中检测对象属性是否为未定义的最佳方式。

if (typeof xyz === "undefined")
     alert("xyz is undefined");
if (typeof xyz === "undefined")
  alert("Varaible is undefined");
else
  alert("Variable is defined"); 

执行一下

如下示例检测变量的数据类型。

JS代码

var index = 8;
  var result = (typeof index === 'number');
  alert(result);
  // Output: true
var description = "w3capi";
  var result = (typeof description === 'string');
  alert(result); 
  // Output: true

执行一下

上一篇:JavaScript:this 操作符
下一篇:JavaScript:void 运算符

相关提问
敬请期待