Maison > interface Web > js tutoriel > le corps du texte

浅玩JavaScript的数据类型判断

高洛峰
Libérer: 2016-11-05 10:12:08
original
1076 Les gens l'ont consulté

前言

平常在需要进行类型判断时,随手拿起typeof就像手枪一样只管突突突...也没有仔细的去了解它的具体特性。
所以这里就利用空闲时间,来做一个较为详细的了解。

首先我们来全面看一遍typeof类型的检测情况:

这里我给一组比较详细的数据类型变量:

var s = new String('abc'),
        n = 123,
        b = true,
        a = new Array(),
        o = new Object(),
        d = new Date(),
        u = undefined,
        f = function(){},
        w = window,
        doc = document,
        r = new RegExp(),
        m = Math,
        t = window.setTimeout,
        _s = '123',
        _n = null,
        _d = document.body,
        _nan = NaN;
Copier après la connexion

下面我们用typeof分别来检测这些变量的数据类型,看看具体的返回结果:

typeof s --> string
	typeof n --> number
	typeof b --> boolean
	typeof a --> object
	typeof o --> object
	typeof d --> object
	typeof u --> undefined
	typeof f --> function
	typeof w --> object
	typeof doc --> object
	typeof r --> object
	typeof m --> object
	typoef t --> function
	typeof _s --> number
	typoef _n --> object
	typeof _d --> object
	typeof _nan --> number
Copier après la connexion

通过以上测试,可以很肯定的说typeof最多只可检查5种数据类型: string,number,boolean,underfined,object 。
实际上JavaScript也只有这5种数据类型。
像Date、Array、Function、HTMLElement、Math、RegExp这些数据,在JavaScript中,他们都是Object对象的再次包装,所以用typeof检测它们就会返回 object 类型。
但是在实际的运用中,如果将 Date、Array、Function、HTMLElement、Math、RegExp 都作为object类型看待,就很不切实际。
幸运的是,我们可以从这些对象的构造函数(constructor)上获得到代表它们具体的含义的信息。

例如:

a.constructor.toString() -- > "function Array() { [native code] }";
Copier après la connexion

所以通过结合typeof、Object.constructor 这两种方法,自己编写了一个检测类型的方法:

function getType(){

    var value = arguments[0],
        type = function(){
            return /\w+\s(\w+)\(\)\s.+?/.test(value.constructor.toString()) ? RegExp.$1.toLowerCase() : 'arguments except'; 
        };

    if(typeof value){
        return value !== null ?  value !== undefined ? type() : 'undefined' :  'null';
    }else{
        return 'undefined';
    }

}
Copier après la connexion

另外对于typeof在使用上还有一个小技巧。用typeof检测一个不存在“变量”的数据类型时,并不会报错,而是返回undefined。
而在以前,对与不确定的代码,我们都是通过try{}catch(e){...} 进行尝试运行的。

最后在查阅typeof的资料时。顺便也简单的看了下 instanceof 运算符的介绍。
总的来说,instanceof运算符是用于“检测左侧参数是否是右侧参数的一个实例”。如果是,则返回true,否则返回false。
示例:

var p = new person();
p instanceof person // --> true;
Copier après la connexion

在这个示例中因为p是构造函数的person的一个实例,所以通过instanceof运算符得到的就是true。
这一点,可以在 p.constructor == 'function person(){}' 得到应征。
再稍微复杂的还有:

function person(){}
function animal(){}

persion.prototype = new animal();
var p = new person();
p instanceof persion() //--> true
p instanceof animal() //--> true
Copier après la connexion


Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!