用js如何判断数据类型

来源:互联网 发布:windows快捷键虚拟桌面 编辑:程序博客网 时间:2024/04/29 10:02

常见的数据类型有:

  • 原始类型:
    • Boolean - - 布尔值(返回值为false或true)
    • Null
    • Undefined- - 未定义变量
    • Number- - 数字型
    • String- -  字符串型
  • Objec t- - 如果变量是一种引用类型或 Null 类型的

根据js的数据类型,举几个例子:

var a;var b=1;var c="1";var d=[1,2,3];var e=function(){};

方法一:typeof来检查数据类型

typeof a -->undefined;

typeof b -->number;

typeof c -->string;

typeof d -->object;

typeof e -->function;

通过返回的布尔值来判断数据类型

typeof a =="undefined";  //true

typeof b =="number";  //true

typeof c =="string";  //true

typeof d =="object";  //true

typeof e =="function";  //true

方法二:instanceof来判断数据类型

 

a instanceof Undefined;  //true

b instanceof Number;  //true

c instanceof String;  //true

d instanceof Object;  //true

e instanceof Function;  //true

注意:instanceof后面一定要是对象类型,并且大小写不能错


方法三:constructor来判断数据类型

a.constructor==Undefined;  //true

b.constructor ==Number;  //true

c.constructor ==String;  //true

d.constructor==Array;  //true

e.constructor ==Function;  //true


方法四:prototype判断数据类型

Object.prototype.toString.call(a) === ‘[object Undefined]’);  // true;

Object.prototype.toString.call(b) === ‘[object Number]’);  // true;

Object.prototype.toString.call(c) === ‘[object String]’);  // true;

Object.prototype.toString.call(d) === ‘[object Array]’);  // true;

Object.prototype.toString.call(e) === ‘[object Function]’);  // true;

0 0