1.typeof方法
此類方法適用于非object的類型判斷,返回變量類型缝左。
var str = "abc";
var num = 123;
var arr = [1,2,3];
var boolean = true;
var obj = {a:1,b:2,c:3};
var fn1 = function(){alert(123);};
var date = new Date ();
var aaa;
var bbb = null;
console.log(typeof str); //string
console.log(typeof num); //number
console.log(typeof arr); //object
console.log(typeof boolean); //boolean
console.log(typeof obj); //object
console.log(typeof fn1); //function
console.log(typeof date); //object
console.log(typeof aaa); //undefined
console.log(typeof bbb); //object
注意:
- i. typeof 可以判斷function類型的變量姑食;
- ii. typeof 不能判斷object的具體類型(數(shù)組/對(duì)象/null/日期均返回object類型)宰僧;
- iii. 已聲明但未初始化(賦值)的變量typeof返回undefined主巍,初始化值為null的變量typeof返回object
- iv. typeof NaN返回"number"
2.instanceof方法——判斷對(duì)象類型(基于原型鏈的操作符)
此方法適用于已知變量類型為object,判斷該對(duì)象的具體類型(注意大小寫)碱蒙,返回值為布爾值荠瘪。
obj instanceof Object
- 左操作數(shù)obj :期望值是一個(gè)對(duì)象,如果是基本類型赛惩,返回false
- 右操作符Object : 函數(shù)對(duì)象或函數(shù)構(gòu)造器哀墓, 如果不是,拋出typeerror異常
console.log(arr instanceof Array); //true
console.log(fn1 instanceof Function); //true
console.log(date instanceof Date); //true
console.log(obj instanceof Object); //true
3.constructor方法
類似于instanceof方法喷兼,但在繼承時(shí)會(huì)出錯(cuò)篮绰,慎用
console.log(arr.constructor === Array); //true
console.log(fn1.constructor === Function); //true
console.log(date.constructor === Date); //true
console.log(obj.constructor === Object); //true
在出現(xiàn)繼承時(shí):
function Student () {}; //構(gòu)造函數(shù)Student
function Person () {}; //構(gòu)造函數(shù)Person
Student.prototype = new Person(); //Student繼承自Person
var Jack = new Student(); //通過構(gòu)造函數(shù)Student創(chuàng)建一個(gè)名為Jack的對(duì)象
console.log(Jack.constructor === Person); //true
console.log(Jack.constructor === Student); //flase
//但用instanceof方法時(shí),對(duì)象直接繼承和間接繼承都報(bào)true
console.log(Jack instanceof Person); //true
console.log(Jack instanceof Student); //true
4.prototype方法(通用)
此方法為通用方法季惯,但較繁瑣吠各,注意大小寫
console.log(Object.prototype.toString.call(str); //[Object String]
console.log(Object.prototype.toString.call(num); //[Object Number]
console.log(Object.prototype.toString.call(fn); //[Object Function]
console.log(Object.prototype.toString.call(obj); //[Object Object]
console.log(Object.prototype.toString.call(date); //[Object Date]
console.log(Object.prototype.toString.call(aaa); //[Object Undefined]
console.log(Object.prototype.toString.call(bbb); //[Object Null]
console.log(Object.prototype.toString.call(arr); //[Object Array]
console.log(Object.prototype.toString.call(boolean); //[Object Boolean]
小結(jié):
- a. 不判斷Object具體類型時(shí):用typeof方法判斷即可臀突;
- b. 僅判斷Object具體類型時(shí):用instanceof或constructor方法,但constructor方法在有繼承的情況下會(huì)出錯(cuò)贾漏,盡量使用instanceof
- c. 非Object類型與Object具體類型都要判斷時(shí):用prototype方法候学,注意大小寫