在JS中數據有七種內置類型:空值( null)、未定義( undefined)、布爾值( boolean)、數字( number)、字符串( string)、對象( object)、符號( symbol, ES6 中新增)
有的時候我們對數據的類型進行判定,在JS中可以通過typeof運算符、instanceof運算符、Object.prototype.toString方法來判斷數據的類型
typeof運算符
typeof運算符返回類型的字符串值
typeof undefined // 'undefined'
typeof null // 'object',特殊情況
typeof 1 // 'number'
typeof '1' // 'string'
typeof true // 'boolean'
typeof function () {} // 'function'
typeof { name: 'a' } // 'object'
typeof [1] // 'object'
typeof Symbol() // "symbol"
instanceof運算符
在上面使用typeof檢測數組和對象時,返回的都是'object',這種情況下不能準確獲取對象的類型。這時候可以使用instanceof運算符, instanceof運算符檢測是什么類型的對象,返回一個布爾值。
instanceof只能用來判斷對象和函數,不能用來判斷字符串和數字等,除非字符串和數字是構造函數生成的,instanceof的原理是檢測對象的原型鏈是否指向構造函數的prototype對象。
var a = [1];
a instanceof Array // true
a instanceof Object // true
function A(){}
function B(){}
B.prototype = new A();//JavaScript 原型繼承
var b = new B();
console.log(b instanceof B) //true
console.log(b instanceof A) //true
Object instanceof Object // true
var c = /a/g;
c instanceof RegExp; // true
前面說typeof null === 'object'
,但是null instanceof Object
會返回false
,正確檢測null可以使用。
var a = null;
(!a && typeof a === "object"); // true
Object.prototype.toString方法
Object.prototype.toString方法可以準確區分數據的類型,Object.prototype.toString方法被調用時會執行以下步驟:
如果this的值為undefined,則返回"[object Undefined]"
如果this的值為null,則返回"[object Null]"
讓O成為調用ToObject(this)的結果.
讓class成為O的內部屬性[[Class]]的值.
-
返回三個字符串"[object ", class, 以及 "]"連接后的新字符串
Object.prototype.toString.call(1) // [object Number] Object.prototype.toString.call('1') // [object String] 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({}) // [object Object] Object.prototype.toString.call([]) // [object Array] Object.prototype.toString.call(new Date) // [object Date] Object.prototype.toString.call(new Error()) // [object Error] Object.prototype.toString.call(/a/) // [object RegExp] Object.prototype.toString.call(function () {}) // [object Function]
其他檢測方法
-
isNaN()函數,使用isNaN()參數可以轉化為數字(相當于使用Number()函數的結果)則返回false,反之返回true;
isNaN(NaN); // true isNaN(10); // false isNaN('10'); // false isNaN('10a'); // true isNaN(true); // false isNaN({valueOf: function () {return 10;}}); // false
-
Array.isArray(),參數為數組返回true,反之返回false;
Array.isArray([]); // true Array.isArray(10); // false