JavaScript之類型判斷

好久沒有寫博客了,現在重新開始。今天寫的是一個關於JavaScript類型判斷的問題


JavaScript判斷類型常見的是有四種方法——typeof,toString,instanceof和constructor

本次主要說typeof和toString

type

typeof用於區分對象和原始類型

基本類型

function test(o){
    console.log(typeof o)
}
test(undefined);
test(null);
test(3);
test("Sadf");
test({});
test(true)
運行結果爲


可以看到,typeof在基本類型上除了null還是不錯的


其它類型

// Symbols
typeof Symbol() === 'symbol'
typeof Symbol('foo') === 'symbol'
typeof Symbol.iterator === 'symbol'


// Undefined
typeof undefined === 'undefined';
typeof declaredButUndefinedVariable === 'undefined';
typeof undeclaredVariable === 'undefined'; 


// Objects
typeof {a: 1} === 'object';

// use Array.isArray or Object.prototype.toString.call
// to differentiate regular objects from arrays
typeof [1, 2, 4] === 'object';

typeof new Date() === 'object';


// The following is confusing. Don't use!
typeof new Boolean(true) === 'object'; 
typeof new Number(1) === 'object'; 
typeof new String('abc') === 'object';


// Functions
typeof function() {} === 'function';
typeof class C {} === 'function';
typeof Math.sin === 'function';


可以看到,typeof在面對sybol時顯示sybol,面對function,class時顯示function,剩下時候都是顯示object(尤其是數組和包裝類,嚴重影響使用)


下面讓我們看看toString的情況


toString

鑑於toString只有對象上纔有,所以使用以下調用方式

function toStr(o){
    console.log(toString.call(o))
}

toStr(undefined);
toStr(null);
toStr(3);
toStr("adf");
toStr(true);
toStr(Symbol("adsf"))


這一次返回結果還讓人滿意,讓我們進行更復雜的測試

toString.call(new Date);    // [object Date]
toString.call(new String);  // [object String]
toString.call(Math);        // [object Math]

// Since JavaScript 1.8.5
toString.call(undefined);   // [object Undefined]
toString.call(null);        // [object Null]     
toString.call(()=>{console.log("hello"))        //[object Function]
toString.call(class A{})			//[object Function]
toString.call(new Number("123"))		//[object Number]


可以看到,這一次結果還是很滿意的(除了class,不過在JavaScript中class只是一個function的語法糖)




發佈了92 篇原創文章 · 獲贊 30 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章