常用的判斷JS數據類型的方法有以下四種:
### **typeof**: 返回一個表示數據類型的字符串。
```
typeof ''; // string 有效
typeof 1; // number 有效
typeof true; //boolean 有效
typeof undefined; //undefined 有效
typeof null; //object 無效
typeof [] ; //object 無效
typeof new Date(); //object 無效
typeof new RegExp(); //object 無效
typeof console.log; // function 有效
typeof Symbol(); // symbol 有效
```
**說明:**
* 數組和對象返回的都是object,不能用typeof做區分。
### **instanceof**: 用來測試一個對象在其原型鏈中是否存在一個構造函數的 prototype 屬性。簡言之, A instanceof B表示如果A是B的實例,則返回true,否則返回false。
```
[] instanceof Array; //true
{} instanceof Object; //true
null instanceof Object; //false
null instanceof Array; //false
```
**說明:**
* 對于基本數據類型,字面量方式創建出來的結果和實例方式創建的是有一定的區別的:
```
console.log(1 instanceof Number) //false
console.log(new Number(1) instanceof Number) //true
```
* 只要在當前實例的原型鏈上,我們用其檢測出來的結果都是true:
```
var arr = [1, 2, 3];
console.log(arr instanceof Array) // true
console.log(arr instanceof Object); // true
```
* 由于瀏覽器對于特殊數據類型null和undefined的限制作用,無法使用instanceof進行判斷。
### **constructor**:功能和instanceof類似,但是可以用于判斷基本數據類型。
```
let a = 1, b = '', c = {}, d = [];
a.constructor:
? Number() { [native code] }
b.constructor:
? String() { [native code] }
c.constructor:
? Object() { [native code] }
d.constructor:
? Array() { [native code] }
```
**說明:**
* null和undefined是比較特殊的基本數據類型,不存在constructor,無法通過此方法進行判斷:

### **Object.prototype.toString.call()**
```
Object.prototype.toString.call('') ; // [object String]
Object.prototype.toString.call(1) ; // [object Number]
Object.prototype.toString.call(true) ; // [object Boolean]
Object.prototype.toString.call(undefined) ; // [object Undefined]
Object.prototype.toString.call(null) ; // [object Null]
Object.prototype.toString.call(new Date()) ; // [object Date]
Object.prototype.toString.call([]) ; // [object Array]
Object.prototype.toString.call(new RegExp()) ; // [object RegExp]
Object.prototype.toString.call(new Error()) ; // [object Error]
Object.prototype.toString.call(document) ; // [object HTMLDocument]
Object.prototype.toString.call(window) ; //[object Window] window是全局對象global的引用
```