判斷資料型別的方法
阿新 • • 發佈:2021-12-16
四種方式
1.typeof
- 對於基本型別,除 null 以外,均可以返回正確的結果。
- 對於引用型別,除 function 以外,一律返回 object 型別。
- 對於 null ,返回 object 型別。
- 對於 function 返回 function 型別。
2.instanceof
- instanceof 只能用來判斷兩個物件是否屬於例項關係, 而不能判斷一個物件例項具體屬於哪種型別。
[] instanceof Array;
// true
{} instanceof Object;
// true
new
Date() instanceof Date;
// true
3.constructor
- 利用原型物件上的 constructor 引用了自身
- null 和 undefined 是無效的物件,因此是不會有 constructor 存在的,這兩種型別的資料需要通過其他方式來判斷。
- 函式的 constructor 是不穩定的,這個主要體現在自定義物件上,當開發者重寫 prototype 後,原有的 constructor 引用會丟失
- [].constructor === Array
4.toString
Object.prototype.toString.call(
''
) ;
// [object String]
Object.prototype.toString.call(1) ;
// [object Number]
Object.prototype.toString.call(
true
) ;
// [object Boolean]
Object.prototype.toString.call(Symbol());
//[object Symbol]
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]
Object.prototype.toString.call(document) ;
// [object HTMLDocument]