zoukankan      html  css  js  c++  java
  • 各种数据类型的判断方法

      在编程过程中,经常需要判断某种是否是某种数据类型,或者某种数据类型是否为空。方法很多,也比较容易记混乱,这篇文章也是给自己理理思路,把各种判断的方法总结下。
      首先,在js中有5种基本类型:Number String undefined Null Boolean 和一种引用类型 Object, 在引用类型中又可分为 Array数组,Function函数,Object对象,Date,RegExp 类型。

    typeof 操作符

    typeof 操作符用来检测基本数据类型是没有问题的,除了null ,typeof null === ‘object’ ,比如需要判断一个数是否为数字,只需要这样比较:

    1
    2
    3
    4
    if(typeof 3 === 'number'){

    }
    // 不是数字

    对于各种类型 typeof 的比较值:

    1
    2
    3
    4
    5
    6
    typeof 3 // "number"
    typeof "abc" // "string"
    typeof {} // "object"
    typeof true // "boolean"
    typeof undefined // "undefined"
    typeof function(){} // "function"

    instanceof 操作符

    instanceof是通过原型链来检查类型的,所以适用于任何”object”的类型检查。

    1
    2
    3
    4
    5
    6
    7
    8
    // 比如直接原型关系
    function (){ }
    (new Animal) instanceof Animal // true

    // 原型链上的间接原型
    function Cat(){}
    Cat.prototype = new Animal
    (new Cat) instanceof Animal // true

    instanceof 不能检测基本数据类型。

    Object.prototype.toString

    是最为可靠的类型检测手段,它会将当前对象转换为字符串并输出。Object.prototype.toString也不是完美的,它无法检测用户自定义类型。 因为Object.prototype是不知道用户会创造什么类型的, 它只能检测ECMA标准中的那些内置类型。

    1
    2
    大专栏  各种数据类型的判断方法>3
    4
    5
    6
    7
    8
    9
    10
    Object.prototype.toString.call(new Date);    // [object Date]
    Object.prototype.toString.call(new String); // [object String]
    Object.prototype.toString.call(Math); // [object Math]
    Object.prototype.toString.call(3); // [object Number]
    Object.prototype.toString.call([]); // [object Array]
    Object.prototype.toString.call({}); // [object Object]

    // Since JavaScript 1.8.5
    Object.prototype.toString.call(undefined); // [object Undefined]
    Object.prototype.toString.call(null); // [object Null]

    类型检测总结

    ==typeof==只能检测基本数据类型,对于null还有Bug;
    ==instanceof==适用于检测对象,它是基于原型链运作的;
    ==constructor==指向的是最初创建者,而且容易伪造,不适合做类型判断;
    ==Object.prototype.toString==适用于ECMA内置JavaScript类型(包括基本数据类型和内置对象)的类型判断;
    基于引用判等的类型检查都有跨窗口问题,比如instanceof和constructor。
    总之,如果你要判断的是基本数据类型或JavaScript内置对象,使用toString; 如果要判断的时自定义类型,请使用instanceof。

    数组是否为空

    这个可以通过判断数组的长度来进行判断,空数组的长度为0,但是有一种情况是:如果数组的key为字符串时,.length返回的也是0

    1
    2
    3
    4
    var s = [];
    s['job'] = '程序员';
    s['name'] = '张三';
    alert(s.length); //0

    but,应该不会出现这种情况。一般都作为对象了。

    对象是否为空

    这里借鉴一个jquery钟的 isEmptyObject 方法:遍历对象,如果不为空 则返回 false ,为空则返回true。

    1
    2
    3
    4
    5
    6
    7
    function isEmptyObject(e) {  
    var t;
    for (t in e) {
    return false;
    }
    return true
    }
  • 相关阅读:
    WCF+EntityFramework+mysql总结
    实现Win7远程桌面关机和重启
    EF 4.1 一些操作
    Ado.net利用反射执行SQL得到实体
    .net IL 指令速查
    VS2010 /VC/bin/rcdll.dll 无法找到资源编译器
    Win7下 httpRequest带证书请求https网站
    VS2010 自动关闭的问题解决方法
    Android 之 悬浮窗口
    论 Java 中获取一组不重复的随机数之性能问题
  • 原文地址:https://www.cnblogs.com/lijianming180/p/12251224.html
Copyright © 2011-2022 走看看