上一篇随笔中总结了js数据类型检测的几个方法和jQuery的工具方法type方法,本篇要分析几个方法都依赖type方法,因此不了解type方法的请先参看http://www.cnblogs.com/yy-hh/p/4667950.html html
用于测试是否为函数的对象jquery
示例:数组
function stub() {} var objs = [ function () {}, { x:15, y:20 }, null, stub, "function" ]; jQuery.each(objs, function (i) { var isFunc = jQuery.isFunction(objs[i]); $("span:eq( " + i + ")").text(isFunc); })
运行结果:app
[ true,false,false,true,false ]
源码分析:dom
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) { return jQuery.type(obj) === "function"; },
首先就告诉你自从1.3版本就有bug ,一些dom方法和函数例如alert在ie里面会返回false,看了下这个bug,由于toString方法和valueOf方法都会被重写因此有人就提出了用instanceof方法检测可是在ie6仍是有问题。目前为止这个bug尚未关闭具体你们能够从参考官网bug页由于我分析的是1.7.1因此就先按照这个版原本,这个方法就是简单的调用type方法判断其返回结果是否为字符串function函数
用于测试是否为数组的对象工具
示例:源码分析
$("b").append( " + $.isArray([]) );//<b>true</b>
源码分析:测试
isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; },
跟isFunctoin同样直接使用type方法的返回结果spa
肯定它的参数是不是一个数字。
$.isNumeric() 方法检查它的参数是否表明一个数值。若是是这样,它返回 true。不然,它返回false。该参数能够是任何类型的
示例:
$.isNumeric("-10"); // true
$.isNumeric(16); // true
$.isNumeric(0xFF); // true
$.isNumeric("0xFF"); // true
$.isNumeric("8e5"); // true (exponential notation string)
$.isNumeric(3.1415); // true
$.isNumeric(+10); // true
$.isNumeric(0144); // true (octal integer literal)
$.isNumeric(""); // false
$.isNumeric({}); // false (empty object)
$.isNumeric(NaN); // false
$.isNumeric(null); // false
$.isNumeric(true); // false
$.isNumeric(Infinity); // false
$.isNumeric(undefined); // false
源码分析:
isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); },
这个方法不是判断Number类型而是看起来像数字的类型只要传进去的参数包含数字那么就会返回true,首先使用parseFloat方法把参数转为数组,此方法会保留参数中的数字部分过滤掉其余部分,若是结果不是NaN也没有超过最大值就是true不然返回false
用于测试是否为window对象
源码分析:
// A crude way of determining if an object is a window
isWindow: function( obj ) { return obj && typeof obj === "object" && "setInterval" in obj; },
一种粗略的方法判断对象是window,若是知足传进来的是对象并且具备setInterval方法则认为该对象为window对象,如今这个方法已经改成判断是不是窗口对象了具体之后在分析