javascript判斷數據類型,判斷是否是數組

數據類型判斷

  • typeof 操作符返回一個字符串,指示未經計算的操作數的類型。
    <pre>
    var a = 'abc'; console.log(typeof a);//string
    var b = 1; console.log(typeof b); //number
    var c = false; console.log(typeof c); //boolean
    console.log(typeof undefined); //undefined
    console.log(typeof null); //object
    console.log(typeof {});// object
    console.log(typeof []);//object
    console.log(typeof (function(){}));//function
    </pre>

數組類型判斷

  • instanceof,判斷一個變量是否某個對象的實例
    <pre>
    var arr = [];
    arr instanceof Array;//true
    </pre>
  • constructor屬性返回對創建此對象的函數的引用。
    <pre>
    var arr = [];
    arr.constructor === Array; //true
    </pre>
  • Object.prototype.toString(),為了每個對象都能通過 Object.prototype.toString() 來檢測,需要以 Function.prototype.call() 或者 Function.prototype.apply() 的形式來調用,把需要檢測的對象作為第一個參數傳入。
    <pre>
    var arr = [];
    Object.prototype.toString.call(arr) === '[object Array]';//true
    //其他類型判斷
    Object.prototype.toString.call(123) === '[object Number]';
    Object.prototype.toString.call('abc')) === '[object String]';
    Object.prototype.toString.call(undefined) === '[object Undefined]';
    Object.prototype.toString.call(true) === '[object Boolean]';
    Object.prototype.toString.call(function(){}) === '[object Function]';
    Object.prototype.toString.call(new RegExp()) === '[object RegExp]';
    Object.prototype.toString.call(null) === '[object Null]';
    </pre>
  • Array.isArray() 確定傳遞的值是否為Array。
    <pre>
    var arr = [];
    Array.isArray(arr);//true
    </pre>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容