JQuery_2.1.0_日記 5.1

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 ;
       },
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章