1. 程式人生 > >JS判斷資料型別的三種方法

JS判斷資料型別的三種方法

JavaScript 中常見的幾種資料型別:

基本型別:string,number,boolean

特殊型別:undefined,null

引用型別:Object,Function,Function,Array,Date,...

typeof

typeof 返回一個表示資料型別的字串,返回結果包括:number、boolean、string、object、undefined、function等6種資料型別。如果是判斷一個基本的型別用typeof就是可以的。

1
2
3
4
5
6
7
8
9
typeof ''; // string 有效
typeof 1; // number 有效
typeof true; //boolean 有效 typeof undefined; //undefined 有效 typeof null; //object 無效 typeof [] ; //object 無效 typeof new Function(); // function 有效 typeof new Date(); //object 無效 typeof new RegExp(); //object 無效

typeof 可以對JS基礎資料型別做出準確的判斷,而對於引用型別返回的基本上都是object, 其實返回object也沒有錯,因為所有物件的原型鏈最終都指向了Object,Object是所有物件的`祖宗`。

如果判斷的是引用型別的話,typeof 就顯得有些力不從心了。

instanceof

instanceof 是用來判斷 A 是否為 B 的例項對,表示式為:A instanceof B,如果A是B的例項,則返回true,否則返回false。 在這裡需要特別注意的是:instanceof檢測的是原型

1
2
3
[] instanceof Array; //true
{} instanceof Object;//true
new Date() instanceof Date;//true

Object.prototype.toString 

toString是Object原型物件上的一個方法,該方法預設返回其呼叫者的具體型別,更嚴格的講,是 toString執行時this指向的物件型別, 返回的型別格式為[object,xxx],xxx是具體的資料型別,其中包括:String,Number,Boolean,Undefined,Null,Function,Date,Array,RegExp,Error,HTMLDocument,... 基本上所有物件的型別都可以通過這個方法獲取到。

1
2
3
4
5
6
7
8
9
10
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 Function()) ; // [object Function]
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]