typeof 適合基本類型及function檢測,遇到null失效。
10余年的鞏義網站建設經驗,針對設計、前端、開發、售后、文案、推廣等六對一服務,響應快,48小時及時工作處理。成都營銷網站建設的優勢是能夠根據用戶設備顯示端的尺寸不同,自動調整鞏義建站的顯示方式,使網站能夠適用不同顯示終端,在瀏覽器中調整網站的寬度,無論在任何一種瀏覽器上瀏覽網站,都能展現優雅布局與設計,從而大程度地提升瀏覽體驗。創新互聯建站從事“鞏義網站設計”,“鞏義網站推廣”以來,每個客戶項目都認真落實執行。
typeof 100; // "number"
typeof true; // "boolean"
typeof fun(); // "function"
typeof NaN; // "number"
typeof undefined; // "undefined"
typeof null; // "object"
typeof new Object(); // "object"
typeof [1,2]; // "object"
instanceof一般用于對象類型的判斷,是基于原型鏈的判斷。
//obj instanceof Object
[1,2] instanceof Array === true
new Object() instanceof Array === false
function Student(){}
function Teacher(){}
var s = new Student()
console.log(s instanceof Student) // true
console.log(s instanceof Teacher) // false
Student.prototype = new Teacher()
var s2 = new Student()
console.log(s2 instanceof Student) // true
console.log(s2 instanceof Teacher) // true
PS:適合自定義對象,也可以用來檢測原生對象。不同window或iframe間的對象類型檢測不能用instanceof。
通過{}.toString拿到,適合內置對象和基本類型,遇到null和undefined失效(IE678返回[object Object])。
Object.prototype.toString.apply([]) === "[object Array]"
Object.prototype.toString.apply(function(){}) === "[object Function]"
Object.prototype.toString.apply(null) === "[object Null]" // IE6/7/8返回"[object Object]"
Object.prototype.toString.apply(undefined) === "[object Undefined]"
Object.prototype.toString.apply(123) === "[object Number]"
Object.prototype.toString.apply('123') === "[object String]"
Object.prototype.toString.apply(true) === "[object Boolean]"
console.log(Object.prototype.toString.apply(new Object())) //[object Object]
function Student(){}
var s = new Student()
console.log(Object.prototype.toString.apply(s)) //[object Object]
console.log(Object.prototype.toString.apply(window)) // [object Window]
console.log(Object.prototype.toString.apply(new Date())) //[object Date]