检测类型

JavaScript 是弱类型语言,对类型没有严格限制,但是在程序中经常需要对类型进行检测和转换,下面结合示例介绍类型检测和转换的技巧。

使用 typeof 检测类型

typeof 运算符专门用来测试值的类型,特别对于原始值有效,而对于对象类型的数据,如数组、对象等,返回的值都是字符串”object”。

alert( typeof 1);           //返回字符串"number" 
alert( typeof "a");         //返回字符串"string"
alert( typeof true);        //返回字符串"boolean" 
alert( typeof {});          //返回字符串"object" 
alert( typeof [] );         //返回字符串"object"
alert( typeof function(){});//返回字符串"function" 
alert( typeof undefined);   //返回字符串"undefined" 
alert( typeof null);        //返回字符串"object" 
alert( typeof NaN);         //返回字符串"number"
//由于 null 值返回类型为 object,用户可以定义一个检测简单数据类型的一般方法。 function type(o) { return (o === null ) ? "null" : (typeof o); //如果是 null 值,则返回字符串"null",否则返回(typeof o)表达式的值 }

使用 constructor 检测类型

对于对象、数组等复杂数据,可以使用 Object 对象的 constructor 属性进行检测。 constructor 表示构造器,该属性值引用的是构造当前对象的函数。

var o = {}; 
var a = []; 
alert( o.constructor == Object); //返回 true 
alert( a.constructor == Array);  //返回 true

使用 constructor 属性可以检测绝大部分数据的类型,但对于 undefined 和 null 特殊值, 就不能够使用 constructor 属性,否则会抛出异常。这时可以先把值转换为布尔值,如果为 true,则说明是存在值的, 然后再调用 constructor 属性。

 封装类型检测方法: toString()

使用 toString() 方法可以设计一种更安全的检测 JavaScript 数据类型的方法,用户还可以根据开发需 要进一步补充检测类型的范围。 由 Object 对象定义的 toString() 方法返回的字符串形式是[object class],其中object是大类表示对象的通用类型,class是小类表示对象的内部类型(Array,Function,Date,Math,Error......),用户自定义对象为object,class 值提供的信息与对象的 constructor 属性值相似,但是 class 值是以字符串的形式提供这些信息的,这在特定的环境中是非常有用的。如果使用 typeof运算符来检测,则所有对象的 class 值都为“Object” 或“Function”。所以不能够提供有效信息。 但是,要获取对象的 class 值的唯一方法是必须调用 Object 的原型方法 toString(),因为很多类型对象都会重置 Object 的 toString() 方法,所以不能直接调用对象的 toString() 方法。

var d = new Date(); 
alert(d.toString());   //返回当前 UTC 时间字符串 

var m = Object.prototype.toString; 
alert(m.apply(d));     //返回字符串"[object Date]"
//安全检测 JavaScript 基本数据类型和内置对象 
//参数: o表示检测的值 
//返回值:返回字符串"undefined"、 "number"、"boolean"、"string"、 "function"、 "regexp"、"array"、"date"、"error"、"object"或"null"

function typeOf (o) { 
    var _toString = Object.prototype.toString; 
    //获取对象的 toString ()方法引用 
    //列举基本数据类型和内置对象类型,你还可以进一步补充该数组的检测数据类型范围 
    var _type = { 
        "undefined":"undefined", 
        "number":"number", 
        "boolean":"boolean",
        "string":"string",
        "[object Function]":"function",
        "[object RegExp]":"regexp", 
        "[object Array]":"array",
        "[object Date]":"date",
        "[object Error)":"error" 
    }
    return _type[typeof o] || _type[_toString.call(o)) || (o ? "object" : "null");   //通过把值转换为字符串,然后匹配返回字符串中是否包含特定字符进行检测
}
 

 

posted @ 2019-02-24 18:39  空瓶子装满了  阅读(386)  评论(0编辑  收藏  举报