如何判断数据类型?

缺乏、安全感 2022-05-25 05:50 343阅读 0赞

如何判断数据类型?

JavaScript的基本数据类型:Undefined、Null、Boolean、Number、String

  1. var a = "oiamstring.";
  2. var b = 222;
  3. var c= [1,2,3];
  4. var d = new Date();
  5. var e = function(){alert(111);};
  6. var f = function(){this.name="22";};

1.在不知道数据类型的情况下:typeof

  1. alert(typeof a); ------------> string
  2. alert(typeof b); ------------> number
  3. alert(typeof c); ------------> object
  4. alert(typeof d); ------------> object
  5. alert(typeof e); ------------> function
  6. alert(typeof f); ------------> function
  7. 其中typeof返回的类型都是字符串形式,需注意,例如:
  8. alert(typeof a == "string"); -------------> true
  9. alert(typeof a == String); ---------------> false
  10. 另外typeof 可以判断function的类型;在判断除Object类型的对象时比较方便。

2.已知对象类型的情况下:instanceof

  1. alert(c instanceof Array) ---------------> true
  2. alert(d instanceof Date)
  3. alert(f instanceof Function) ------------> true
  4. alert(f instanceof function) ------------> false
  5. 注意:instanceof 后面一定要是对象类型,并且大小写不能错,该方法适合一些条件选择或分支

发表评论

表情:
评论列表 (有 0 条评论,343人围观)

还没有评论,来说两句吧...

相关阅读

    相关 如何判断js中数据类型

    如何判断js中数据类型 方法一、js内置方法typeof 检测基本数据类型的最佳选择是使用typeof typeof 来判断数据类型,只能区分基本类型,即 “number...