1. 程式人生 > >JS中檢測資料型別的多種方法

JS中檢測資料型別的多種方法

面試當中經常會問到檢測 js 的資料型別,我在工作當中也會用到這些方法。讓我們一起走起!!!

首先給大家上一個案例

1 console.log(typeof "langshen");       // String
2 console.log(typeof 666);              // Number
3 console.log(typeof true);             // Boolean
4 console.log(typeof false);            // Boolean
5 console.log(typeof function(){});     // Function
6 console.log(typeof undefined); // Undefined 7 console.log(typeof null); // Object 8 console.log(typeof []); // Object 9 console.log(typeof {}); // Object

通過這些案例大家不難看出 

第一種 : 當 typeof 檢測基本資料型別(Number、String、Boolean 、Undefined、Null)的時候是沒有問題的。

但是檢測引用型資料型別(Array、Object、RegExp等)

的時候全都是 Object。

由於 typeof 檢測的資料型別不是那麼的 perfect !!!會有侷限性。

使用場景:

      可以判斷傳遞的引數是否有值

1 function fn(a, b) {
2   if (typeof b === "undefined") { // 沒有傳遞引數
3     b = 0;
4   }
5   console.log(a, b); //1 0
6 }
7 fn(1);

 

第二種 : instanceof   檢測一個例項是不是屬於某個類

1 console.log("langshen" instanceof
String); //false 2 console.log(666 instanceof Number); //false 3 console.log(true instanceof Boolean); //false 4 console.log(null instanceof Null); 5 console.log(undefined instanceof Undefined); 6 console.log([] instanceof Array); //true 7 console.log(function(){} instanceof Function); //true 8 console.log({} instanceof Object); //true

 

咱們先不要看 null 和 undefined

首先看基本資料型別,打印出來的都是false,這是為什麼呢?

前三個都是以物件字面量建立的基本資料型別,但是卻不是所屬類的例項,只有例項方式創建出來的才是標準的物件資料型別值

如果我們換種方式來檢測

1 new String("langshen") instanceof String       //true
2 new Number(666) instanceof Number              //true
3 new Boolean(true) instanceof Boolean           //true

當我們通過New的方式去建立基本資料型別就輸出true

所以當我們檢測的資料只要在當前例項的原型鏈上,我們用其檢測出來的結果都是true 。