創(chuàng)新互聯(lián)www.cdcxhl.cn八線動態(tài)BGP香港云服務(wù)器提供商,新人活動買多久送多久,劃算不套路!
這篇文章將為大家詳細(xì)講解有關(guān)判斷JS數(shù)據(jù)類型的方法,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
JavaScript 中常見數(shù)據(jù)類型有Number、String、Boolean、Object、Array、Json、Function、Date、RegExp、Error、undefined、Null等十幾種。ES6還有新增的數(shù)據(jù)類型有Symbol、Set、Map等。在實際應(yīng)用中,我們經(jīng)常需要判斷數(shù)據(jù)類型,現(xiàn)在我歸納幾種方法,希望對大家有所幫助。
typeof 判斷(最常用)
typeof
是 JS 提供的一個運算符,專門用來檢測一個變量的類型 。 typeof
有2種使用方式:typeof(表達(dá)式)和typeof 變量名,第一種是對表達(dá)式做運算,第二種是對變量做運算。
function doSomething() { console.log('Hello World!'); } console.log(typeof 1); // number console.log(typeof 'Hello'); // string console.log(typeof []); // object console.log(typeof {}); // object console.log(typeof doSomething); // function console.log(typeof true); // boolean console.log(typeof new Date()); // object console.log(typeof new RegExp()); // object console.log(typeof JSON.stringify({ name: 'zhencanhua' })); // string console.log(typeof null); // object console.log(typeof undefined); // undefined console.log(typeof (new Error('error!'))); // object console.log(typeof a); // undefined console.log(typeof Symbol()); // symbol console.log(typeof new Set()); // object console.log(typeof new Map()); // object