JavaScript基礎(一) 數據類型

動態類型

JavaScript 是一種弱類型或者說動態語言。這意味着你不用提早聲明變量的類型,在程序運行過程當中,類型會被自動肯定。jquery

數據類型

最新的 ECMAScript 標準定義了 7 種數據類型:瀏覽器

  • 6 種 原始類型:閉包

    • Boolean函數

    • Null優化

    • Undefinedprototype

    • Numbercode

    • String對象

    • Symbol (ECMAScript 6 新定義)ip

  • 和 Object內存

typeof 檢測數據類型

typeof用來檢測給定變量的數據類型,返回下列某個字符串

  • "boolean」 --- 變量是布爾值(true/false)

  • "undefined" --- 變量未定義

  • "string" --- 變量是字符串

  • "number" --- 變量是數值

  • "function" --- 變量是函數

  • "object" --- 變量是對象或null

  • "symbol" --- 變量是Symbol

有這樣一道題目,考察 typeof 返回值類型。

typeof(typeof(new Date()))   //string

可是在實際項目中,typeof 也只是用來判斷變量是undefinedfunction。由於不少類型不能精確的判斷出來,例如:

Value function typeof
"foo" String string
new String("foo") String object
1.2 Number number
new Number(1.2) Number object
true Boolean boolean
new Boolean(true) Boolean object
new Date() Date object
new Error() Error object
[1,2,3] Array object
new Array(1, 2, 3) Array object
new Function("") Function function
/abc/g RegExp object
new RegExp("meow") RegExp object
{} Object object
new Object() Object object
注意
typeof /s/ ===function; // Chrome 1-12 , 不符合 ECMAScript 5.1
typeof /s/ === object; // Firefox 5+ , 符合 ECMAScript 5.1

由上得出結論,當使用檢測結果是objectfunction時,咱們並不能看出實際的數據類型。

推薦使用 Object.prototype.toString(),結合call去實現對變量類型的精準判斷。

Object.prototype.toString.call(null);      //」[object Null]」
Object.prototype.toString.call(undefined); //」[object Undefined]」
Object.prototype.toString.call(「abc」);     //」[object String]」
Object.prototype.toString.call(123);       //」[object Number]」
Object.prototype.toString.call(true);      //」[object Boolean]」

簡單封裝以下:

function _typeof(obj){
  
   if(typeof obj == object || typeof obj == function){
    var type =Object.prototype.toString.call(obj).split("")[1].toLowerCase();
    return type.match(/[a-z]/g).join("");  //正則去除字符串的]
  }
  
  return typeof obj; 
  
}

上面代碼在標準瀏覽器中能夠徹底兼容,可是IE6(雖然如今沒必要兼容,也要了解下)中,卻會出現如下問題:

_typeof(null);        //object
_typeof(undefined);   //object

緣由在於IE6下

Object.prototype.toString.call(undefined);  //」[object Object]」
Object.prototype.toString.call(null);       //」[object Object]」

因此要先添加判斷,使用String()對象將 undefinednull轉爲字符串。代碼以下:

function _typeof (obj){
    
    //注意到這裏是 == 而不是 === ,
    //undefined 值是派生自 null 值的,因此null == undefined 返回true 
    if(obj == null){
        return String(obj)
    }
      
    if(typeof obj == "object"; || typeof obj == "function"){
      var type =Object.prototype.toString.call(obj).split(" ")[1].toLowerCase();
      return type.substring(0,type.length-1); 
    }
    
    return typeof obj; 
    
    }

String()函數遵循下列轉換規則:
若是值有 toString()方法,則調用該方法(沒有參數)並返回相應的結果;
若是值是 null,則返回"null";
若是值是 undefined,則返回"undefined"

這樣對 typeof 的擴展就封裝好了。代碼還有優化空間,這裏再也不繼續。

Jquery已經實現了類型檢測的封裝,jquery.type()的內部實現以下:

//實例對象是能直接使用原型鏈上的方法的
var class2type = {};
var toString = class2type.toString;

jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
  class2type[ "[object " + name + "]" ] = name.toLowerCase();
});

$.type = function( obj ) {
  //若是是null或者undefined,直接轉成String返回
  //注意到這裏是==而不是===,
  //undefined 值是派生自 null 值的,因此null == undefined 返回true 
  if ( obj == null ) {
    return String( obj );
  }
  //當typeof 返回 object或function, 進入core_toString 
  return typeof obj === "object" || typeof obj === "function" ?
    class2type[ core_toString.call(obj) ] || "object":
    typeof obj;
}

Undefined

Undefined 類型只有一個值,即特殊的 undefined。在使用 var 聲明變量但未對其加以初始化時,這個變量的值就是 undefined,例如:

var foo;
alert(foo == undefined);  //true

undefined表示"缺乏值",就是此處應該有一個值,可是尚未定義。
典型用法是:

  1. 變量被聲明瞭,但沒有賦值時,就等於 undefined

  2. 調用函數時,應該提供的參數沒有提供,該參數等於 undefined

  3. 對象沒有賦值的屬性,該屬性的值爲 undefined

  4. 函數沒有返回值時,默認返回 undefined

var name;
alert(name) // undefined

function f(x){console.log(x)}
f() // undefined

var  o = new Object();
alert(o.p) // undefined

var x = f();
alert(x) // undefined

Null

Null 類型是第二個只有一個值的數據類型,這個特殊的值是 null
若是定義的變量準備在未來用於保存對象,那麼最好將該變量初始化爲 null

null 有時會被看成一種對象類型,可是這其實只是語言自己的一個bug,即對 null 執行 typeof null 時會返回字符串"object"

原理是這樣的,不一樣的對象在底層都表示爲二進制,在JavaScript中二進制前三位都爲0的話會被判斷爲object類型,null的二進制表示是全0,天然前三位也是0,因此執行 typeof 時會返回「object」。——《你不知道的JavaScript》

使用null的狀況:

1.DOM,試圖獲取一個不存在的元素返回一個null值,而不是undefined
2.初始化一個對象的值,通常設爲null
3.經過分配null值,有效地清除引用,並假設對象沒有引用其餘代碼,指定垃圾收集,確保回收內存。

var table = document.getElementById("table"); 
console.log(table);  // null

var obj = null; //初始化對象

window.onload = function(){
    var el = document.getElementById("id");
    var id = el.id; //解除循環引用
    el.onclick = function(){
        alert(id); 
    }
    el = null; // 將閉包引用的外部函數中活動對象清除
}

Boolean

Boolean 類型是經常使用的一種類型,只有兩個字面值:truefalse

注意:字面值區分大小寫,True 和 False 不是 Boolean 值。

常常遇到就是其餘數據類型轉爲boolean的問題,只要遵循一個原則:

當值爲""(空字符串)、0NaNnullundefined 時,都轉爲false,其餘狀況都爲true

相關文章
相關標籤/搜索