JQuery工具方法.
(1)$.isNumeric(obj)
此方法判断传入的对象是否是一个数字或者可以转换为数字.
isNumeric: function(
obj ) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly
hex literals ("0x...")
// subtraction forces infinities to NaN
return obj
- parseFloat( obj ) >= 0;
},
用‘-‘号先将obj转换为数字,这么做是因为如果传入的字符串中含有非数字字符,那么obj将被转换为NaN,isNumeric将返回false.
alert( ‘55a‘-0) //NaN
注意:js的原生方法parseFloat在处理16进制字符串时会出现转换错误,他会取16进制的标志0x的0.....
var f = parseFloat(‘0xAAAA‘ ,
2);
alert(f); //0
Test_Script
var obj = {toString: function(){
return ‘6‘ ;
}};
var f = $.isNumeric(obj);
alert(f);//true
(2)isPlainObject(obj)
此方法判断传入的对象是否是‘纯净‘的对象,即使用字面量{},或new Object()创建的对象.
Test_Script
function Person(name, age) {
this .name
= name;
this .age
= age;
};
var p = $.isPlainObject( new Person());
alert(p); //false
alert($.isPlainObject({})); //true
alert($.isPlainObject(document.getElementById( ‘div1‘))); //false
isPlainObject(obj)源码
isPlainObject: function(
obj ) {
//不是object或者是DOM元素或是window返回false
if (
jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow(
obj ) ) {
return false ;
}
// Support: Firefox <20
// The try/catch suppresses exceptions
thrown when attempting to access
// the "constructor" property of certain
host objects, ie. |window.location|
// https://bugzilla.mozilla.org/show_bug.cgi?id=814622
try {
//是自定义对象返回false
//判断自定义对象的依据是如果isPrototypeOf方法是从{}的原型对象中继承来的那么便是自定义对象
if (
obj.constructor &&
!hasOwn.call( obj.constructor.prototype, "isPrototypeOf" )
) {
return false ;
}
} catch (
e ) {
return false ;
}
// If the function hasn‘t returned
already, we‘re confident that
// |obj |
is a plain object, created by {} or constructed with new Object
return true ;
},
Agri-Net 1558 Agri-Net