Js的typeof和Js的基本数据类型

十度 javaScript 2016年03月12日 收藏

本文将从以下几个方面介绍Js的typeof和Js的基本数据类型:

  • ** Js的typeof的用法
  • ** Js的基本数据类型
  • ** 使用基本类型使用typeof的返回结果

** Js的typeof的用法 **

typeof 运算符

返回一个用来表示表达式的数据类型的字符串。

typeof[()expression[]] ;

expression 参数是需要查找类型信息的任意表达式。

说明

typeof 运算符把类型信息当作字符串返回。typeof 返回值有六种可能:

"number," "string," "boolean," "object," "function," 和 "undefined."

typeof 语法中的圆括号是可选项。

** Js的基本数据类型 **

Js的数据类型有七种:对象、字符串、数组、数字、布尔、null、undefined

** 使用基本类型使用typeof的返回结果 **

将Js的基本数据类型与typeof的返回结果进行对比,你会发现,只有两种基本数据类型
在typeof中没有体现出来,这个基本类型是 ** NULL 和 数组 **
那么NULL在typeof中的返回结果是什么?是Object!

  1. //x为对象
  2. typeof(x) === "object"
  3. //x为字符串
  4. typeof(x) === "string"
  5. //x为数组
  6. typeof(x) === "object"
  7. //x为数字
  8. typeof(x) === "number"
  9. //x为布尔值
  10. typeof(x) === "boolean"
  11. //x为null
  12. typeof(null) === "object"
  13. //x未定义
  14. typeof(x) === "undefined"
  15. //x为函数
  16. typeof(x) === "function"

那么如何判断一个变量是否不为空,即不为null或者undefined呢?

  1. //在js的if条件中 表达式为 null/undefined/0/NaN是均为false
  2. var notNull = function(temp)
  3. {
  4. if(typeof(temp)!="undefined" && temp !== 0 && temp)
  5. return false;
  6. return true;
  7. }

If there're any problems,please tell me~,thanks.