js中判断undefined类型

时间:2023-03-08 22:16:14

typeof 运算符返回一个用来表示表达式的数据类型的字符串。可能的字符串有:"number"、"string"、"boolean"、"object"、"function" 和 "undefined"。

  • typeof的运算数定义了未初始化,返回的就是 "undefined".
  • 运算数为数字 typeof(x) = "number"
  • 字符串 typeof(x) = "string"
  • 布尔值 typeof(x) = "boolean"
  • 对象,数组和null typeof(x) = "object"
  • 函数 typeof(x) = "function"

typeof在两种情况下会返回"undefined":一个变量没有被声明的时候,和一个变量的值是undefined的时候。

例如:

if(typeof (document.all("selection").length) == "undefined")
alert("length没有定义");
alert(typeof (123));//typeof(123)返回"number"
alert(typeof ("123"));//typeof("123")返回"string"