文章首发:http://www.cnblogs.com/sPRying/p/4349426.html
本文罗列了一般Js类型检测的方法,是构建Js知识体系的一小块,这篇文章是我很早之前总结的。
var obtainType = function(o){ var t; if(o === null ) return “null”; else if(o !== o) return “NaN”; else if( (t = typeof o) !== ‘object’) return t;}可以识别出null、NaN string number boolean undefined function。上面最后只剩下object,比如数组的识别,自定义类型的识别3. 数组等原生类型的识别,可以采用如下
function obtainType(type) { return function (obj) { return Object.prototype.toString.call(obj) === "[object " + type + "]" }}var isObject = isType("Object")var isString = isType("String")var isArray = Array.isArray || isType("Array")var isFunction = isType("Function")4. 自定义类型判断
/** * 返回函数的名字,可能为空串;不是函数,返回null */Function.prototype.getName = function () { if ("name" in this) return this.name; return this.name = this.toString().match(/function/s*([^(]*)/(/)[1];};原生类型和自定义类型的object都可以判断了,于是
/** * 返回:null NaN undefined string number boolean * function Array String Object(包括一些自定义类型) 自定义类型 */var obtainType =function(o){ /** * 获取参数类型 * 对象直接量、Object.create、自定义构造函数的类属性皆为Object; * 识别出原生类型 (内置构造函数和宿主对象) */ function classOf(obj){ return Object.prototype.toString.call(obj).slice(8, -1); } /** * 返回函数的名字,可能为空串;不是函数,返回null */ Function.prototype.getName = function () { if ("name" in this) return this.name; return this.name = this.toString().match(/function/s*([^(]*)/(/)[1]; }; var t, c, n; // 处理null值特殊情形 if (o === null) return "null"; // NaN:和自身值不相等 if (o !== o) return "NaN"; // 识别出原生值类型和函数、undefined if ((t = typeof o) !== "object") return t; // 识别出原生类型 if ((c = classOf(o)) !== "Object") return c; // 返回自定义类型构造函数名字 if (o.constructor && typeof o.constructor === "function" && (n = o.constructor.getName())) return n; return "Object";};
5.
var strObj = new String('abc');typeof strObj // "object"obtainType(strObj) // "String"
// badif (name !== '') { // ...stuff...}// goodif (name) { // ...stuff...}// badif (collection.length > 0) { // ...stuff...}// goodif (collection.length) { // ...stuff...}
新闻热点
疑难解答