1. 程式人生 > >淺談js數據類型識別方法

淺談js數據類型識別方法

簡單 string name bject 識別方法 ber true logs 對象

js有5種基本數據類型 Undefined , Null , Boolean , Number , String 和一種引用類型Object,下面我們就來一一看穿,哦不,識別他們。

  1. typeof

前面5種雖多,但是是基本類型,也容易識別,typeof 操作符就能差不多把他們都識別了,
null 不服的站了出來:“能識別我麽?”,typeof這下犯難了:"你,你你先坐下。" typeof對Object基本上是臉盲的,除了function之外看誰都是Object, 數組是對象,日期對象是對象,正則是對象,對象也是對象。都特麽是對象,typeof 範暈了,只好去請教表哥 instanceof

console.log(typeof "hello");//"string"
console.log(typeof 666);//"number"
console.log(typeof true);//"boolean"
console.log(typeof undefined);//"undefined"
console.log(typeof null);//"object"
console.log(typeof {name: "hello"});//"object" console.log(typeof function(){});//"function" console.log(typeof []);//"object" console.log(typeof new Date);//"object" console.log(typeof /\d/);//"object" function Person(){}; console.log(typeof new Person);//"object"

  簡單說,記住兩點就好了1.typeof可識別出null之外的基本類型 2.不能識別除function之外的具體對象類型

2. instanceof

淺談js數據類型識別方法