如何判断数据类型

阳光穿透心脏的1/2处 2022-06-04 07:08 304阅读 0赞

使用typeof判断数据类型
(1)判断基本数据类型

  1. //数字类型
  2. typeof 1;//"number"
  3. //布尔类型
  4. typeof true;// "boolean"
  5. //字符串类型
  6. typeof "zzz";// "string"
  7. //未定义
  8. typeof undefined;// "undefined"
  9. //对象
  10. function Person(name, age) {
  11. this.name = name;
  12. this.age = age;
  13. }
  14. var person = new Person("Rose", 18);
  15. typeof person;//"object"

在 JavaScript 里使用 typeof 来判断数据类型,只能区分基本类型,即 “number”,”string”,”undefined”,”boolean”,”object” 五种。
对于数组、函数、对象来说,其关系错综复杂,使用 typeof 都会统一返回 “object” 字符串。

值类型的类型判断用typeof,引用类型的类型判断用instanceof。

使用Object.prototype上的原生toString()方法判断数据类型
(1)判断基本 类型

  1. Object.prototype.toString.call(null);//”[object Null]”
  2. Object.prototype.toString.call(undefined);//”[object Undefined]”
  3. Object.prototype.toString.call(“abc”);//”[object String]”
  4. Object.prototype.toString.call(123);//”[object Number]”
  5. Object.prototype.toString.call(true);//”[object Boolean]”

(2)判断原生引用类型

  1. //函数类型
  2. Function fn(){console.log(“test”);}
  3. Object.prototype.toString.call(fn);//”[object Function]”
  4. //日期类型
  5. var date = new Date();
  6. Object.prototype.toString.call(date);//”[object Date]”
  7. //数组类型
  8. var arr = [1,2,3];
  9. Object.prototype.toString.call(arr);//”[object Array]”
  10. //正则表达式
  11. var reg = /[hbc]at/gi;
  12. Object.prototype.toString.call(arr);//”[object Array]”
  13. //自定义类型
  14. function Person(name, age) {
  15. this.name = name;
  16. this.age = age;
  17. }
  18. var person = new Person("Rose", 18);
  19. Object.prototype.toString.call(person ); //”[object Object]”
  20. 很明显这种方法不能准确判断personPerson类的实例,而只能用instanceof 操作符来进行判断,如下所示:
  21. console.log(person instanceof Person);//输出结果为true

(3)判断原生的JSON对象

  1. var isNativeJSON = window.JSON && Object.prototype.toString.call(JSON);
  2. console.log(isNativeJSON);//输出结果为”[object JSON]”说明JSON是原生的,否则不是;

注意:Object.prototype.toString()本身是允许被修改的,而我们目前所讨论的关于Object.prototype.toString()这个方法的应用都是假设toString()方法未被修改为前提的。

发表评论

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

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

相关阅读

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

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