typeof操作符返回一個(gè)字符串,指示未經(jīng)計(jì)算的操作數(shù)的類型抵皱。
// Numbers
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; // 盡管NaN是"Not-A-Number"的縮寫
typeof Number(1) === 'number'; // 但不要使用這種形式!
// Strings
typeof "" === 'string';
typeof "bla" === 'string';
typeof (typeof 1) === 'string'; // typeof總是返回一個(gè)字符串
typeof String("abc") === 'string'; // 但不要使用這種形式!
// Booleans
typeof true === 'boolean';
typeof false === 'boolean';
typeof Boolean(true) === 'boolean'; // 但不要使用這種形式!
// Symbols
typeof Symbol() === 'symbol';
typeof Symbol('foo') === 'symbol';
typeof Symbol.iterator === 'symbol';
// Undefined
typeof undefined === 'undefined';
typeof declaredButUndefinedVariable === 'undefined';
typeof undeclaredVariable === 'undefined';
// Objects
typeof {a:1} === 'object';
// 使用Array.isArray 或者 Object.prototype.toString.call
// 區(qū)分?jǐn)?shù)組,普通對象
typeof [1, 2, 4] === 'object';
typeof new Date() === 'object';
// 下面的容易令人迷惑,不要使用钮呀!
typeof new Boolean(true) === 'object';
typeof new Number(1) ==== 'object';
typeof new String("abc") === 'object';
// 函數(shù)
typeof function(){} === 'function';
typeof Math.sin === 'function';
instanceof 運(yùn)算符用來測試一個(gè)對象在其原型鏈中是否存在一個(gè)構(gòu)造函數(shù)的 prototype 屬性蚂四。用來檢測 constructor.prototype 是否存在于參數(shù) object 的原型鏈上。
var simpleStr = "This is a simple string";
var myString = new String();
var newStr = new String("String created with constructor");
var myDate = new Date();
var myObj = {};
simpleStr instanceof String; // returns false, 檢查原型鏈會找到 undefined
myString instanceof String; // returns true
newStr instanceof String; // returns true
myString instanceof Object; // returns true
myObj instanceof Object; // returns true, despite an undefined prototype
({}) instanceof Object; // returns true, 同上
myString instanceof Date; // returns false
myDate instanceof Date; // returns true
myDate instanceof Object; // returns true
myDate instanceof String; // returns false
補(bǔ)充 Object.prototype.toString:
為了每個(gè)對象都能通過 Object.prototype.toString() 來檢測抑诸,需要以 Function.prototype.call() 或者 Function.prototype.apply() 的形式來調(diào)用奸绷,把需要檢測的對象作為第一個(gè)參數(shù)傳入。
var toString = Object.prototype.toString;
toString.call(new Date); // [object Date]
toString.call(new String); // [object String]
toString.call(Math); // [object Math]
//Since JavaScript 1.8.5
toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]