js如何判断变量的数据类型

如题所述

检测简单的数据类型的方法

    typeof方法用于检测简单的数据类型如typeof 12

    instanceof的实例方法检测如[] instanceof Array // true

    arr.constructor == Array判断arr的构造函数是否为数组,如果是则arr是数组

    Array.isArray([])判断是否是数组

    精确判断数据类型Object.prototype.toString.call(arr)

温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-05-28

使用typeof关键字, 可以得到数据类型的字符串表示(全部为小写):

var  a = 0, b=  true, c="text", d = {x: 0}, e=[1,2];
var f = function(){}, h = null, i

if(typeof a === "number") a = a*2;
typeof a; // "number"
typeof b; // "boolean"
typeof c; // "string"
typeof d; // "object"
typeof e; // "object"
typeof f; // "function"
typeof h; // "object"
typeof i; // "undefined"

可以看出对于null, { }, []返回的类型都是"object", 可进一步判断:

var o = {};
if(typeof o === "object"){
    if(o === null){
        // null
    }else if(Array.isArray(o)){
        // 数组
    }else{
        //普通object对象
    }  
}

一般情况下, 我们不需要全面判断数据类型, 例如往往只要判断是否为xxx数据类型, 用以上方法足够, 但显然上面的方法在判断object对象时有点繁琐, 所以大多数js类库中提供有扩展方法, 这些库一般采用的方法如下:

Object.prototype.toString.call(100);    //"[object Number]"
Object.prototype.toString.call('100');   //"[object String]"
Object.prototype.toString.call(undefined);    //"[object Undefined]"
Object.prototype.toString.call(true);    //"[object Boolean]"
Object.prototype.toString.call(null);    //"[object Null]"
Object.prototype.toString.call({});    //"[object Object]"
Object.prototype.toString.call([]);    //"[object Array]"
Object.prototype.toString.call(function () { });    //"[object Function]"

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网