JavaScript中的數據類型及其檢測

JavaScript中的數據類型及其檢測

1. 數據類型

1.1 基本類型

  • Numberjavascript

  • Stringjava

  • Boolean函數

  • Nullprototype

  • Undefined設計

  • Symbolcode

1.2 引用類型

  • Object對象

  • Arrayip

  • Function原型鏈

  • RegExpget

  • Date

2. 類型檢測

2.1 typeof

var s = 'Nicholas';
var b = true;
var i = 22;
var u;
var n = null;
var o = new Object();
var f = new Function();

console.info(typeof s);     // string
console.info(typeof b);     // boolean
console.info(typeof i);     // number
console.info(typeof u);     // undefined
console.info(typeof n);     // object
console.info(typeof o);     // object
console.info(typeof f);     // function

typeof只能檢測基本數據類型,對於null還有一個Bug

2.2 instanceof

result = variable instanceof constructor
instanceof用於檢測某個對象的原型鏈是否包含某個構造函數的prototype屬性

function C() {}
function D() {}
var o = new C();
o instanceof C     // true, Object.getPrototypeOf(o) === C.prototype
o instanceof D     // false

function Animal() {}
function Cat() {}
Cat.prototype = new Animal();
var b = new Cat();
b instanceof Animal     // true

[1, 2, 3] instanceof Array      // true
/abc/ instanceof RegExp     // true
({}) instanceof Object      // true
(function() {}) instanceof Function     // true

instanceof適用於檢測對象,它是基於原型鏈運做的

2.3 constructor

constructor屬性返回一個指向建立了該對象原型的函數引用,該屬性的值是哪一個函數自己。

function Animal() {}
function Cat() {}
function BadCat() {}
Cat.prototype = new Animal();
BadCat.prototype = new Cat();
var a = new Animal();
a.constructor === Animal    // true
var b = new BadCat();
b.constructor === Animal    // true

constructor指向的是最初建立者,並且易於僞造,不適合作類型判斷

2.4 toString

Object.prototype.toString.call();
({}).toString.call();
window.toString.call();
toString.call();
Object.prototype.toString.call([]);     // [object Array]
Object.prototype.toString.call({});     // [object Object]
Object.prototype.toString.call('');     // [object String]
Object.prototype.toString.call(new Date());     // [object Date]
Object.prototype.toString.call(1);      // [object Number]
Object.prototype.toString.call(function () {});     // [object Function]
Object.prototype.toString.call(/test/i);    // [object RegExp]
Object.prototype.toString.call(true);       // [object Boolean]
Object.prototype.toString.call(null);       // [object Null]
Object.prototype.toString.call();       // [object Undefined]

幾乎十全十美,只是不能檢測用戶自定義類型

2.5 小結

  • typeof只能檢測基本數據類型,對於null還有Bug

  • instanceof適用於檢測對象,它是基於原型鏈運做的

  • constructor指向的是最初建立者,並且容易僞造,不適合作類型判斷

  • toString適用於ECMA內置JavaScript類型(包括基本數據類型和內置對象)的類型判斷

  • 基於引用判等的類型檢查都有跨窗口問題,好比instanceofconstructor

若是你要判斷的是基本數據類型或JavaScript內置對象,使用toString;若是要判斷的是自定義類型,請使用instanceof

參考

相關文章
相關標籤/搜索