Javascript類型判斷

typeof操作符

主要用來檢測基本類型。

// 基本類型
let u = undefined;  // Undefined
let n = null;       // Null   
let b = true;       // Boolean
let str = 'string'; // String
let num = 123;      // Number

// 引用類型Object
let arr = [1,2];
let fun = function(){};
let obj = {};

// es6新增類型Symbol
let symbol = Symbol();

console.log( typeof u ); // undefined
console.log( typeof n ); // object
console.log( typeof b ); // boolean
console.log( typeof str ); // string
console.log( typeof num ); // number

console.log( typeof arr ); // object
console.log( typeof fun ); // function
console.log( typeof object ); // object

console.log( typeof symbol); // symbol

總結:

  1. typeof操作符可以用來檢測基本類型(除了null)和函數。
  2. typeof操作符對null會返回object。
  3. typeof操作符對函數會返回function。
  4. typeof操作符適合用來檢測Undefined、Boolean、String、Number和Function。
  5. typeof操作符可以用檢測Symbol類型。

instanceof操作符

主要用來檢測引用類型

let obj = {};
let arr = [1,2];
console.log( obj instanceof Object ) // true
console.log( arr instanceof Array ) // true

console.log( symbol instanceof Symbol ) // false

總結:
如果變量是給定的引用類型的實例,則返回true

Object.prototype.toString.call()方法

比較安全可靠的類型檢測方法,該方法會拿到變量的構造函數名。
返回的格式是"[object ConstructorName]"。

console.log( Object.prototype.toString.call(u) ); // [object Undefined]
console.log( Object.prototype.toString.call(n) ); // [object Null]
console.log( Object.prototype.toString.call(str) ); // [object String]
console.log( Object.prototype.toString.call(num) ); // [object Number]
console.log( Object.prototype.toString.call(b) );// [object Boolean]
console.log( Object.prototype.toString.call(arr) ); // [object Array]
console.log( Object.prototype.toString.call(fun) ); // [object Function]
console.log( Object.prototype.toString.call(obj) );// [object Object]
console.log( Object.prototype.toString.call(symbol) );// [object Symbol]
// 檢測自定義構造函數生成的變量
function A(){};
let a = new A();
console.log( Object.prototype.toString.call(a) )// [object Object]

總結:
該方法相對安全可靠,但是無法檢測自定義構造函數生成的實例變量。

Jquery的$.type()方法

該方法同typeof一樣返回數據類型,但是比typeof操作符更加精確。

console.log( $.type(n) ) // null
console.log( $.type(arr) ) // array
console.log( $.type(fun) ) // function
console.log( $.type(obj) ) // object
console.log( $.type(symbol) ) // symbol
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容