Javascript類型判斷

typeof操作符

主要用來檢測(cè)基本類型。

// 基本類型
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

總結(jié):

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

instanceof操作符

主要用來檢測(cè)引用類型

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

console.log( symbol instanceof Symbol ) // false

總結(jié):
如果變量是給定的引用類型的實(shí)例,則返回true

Object.prototype.toString.call()方法

比較安全可靠的類型檢測(cè)方法,該方法會(huì)拿到變量的構(gòu)造函數(shù)名。
返回的格式是"[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]
// 檢測(cè)自定義構(gòu)造函數(shù)生成的變量
function A(){};
let a = new A();
console.log( Object.prototype.toString.call(a) )// [object Object]

總結(jié):
該方法相對(duì)安全可靠,但是無法檢測(cè)自定義構(gòu)造函數(shù)生成的實(shí)例變量。

Jquery的$.type()方法

該方法同typeof一樣返回?cái)?shù)據(jù)類型,但是比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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容