- 【 方法一 :typeof 】
作用 : 区分基本数据类型。
语法 : typeof(变量名)。
返回值 : 对应的数据类型。
存在的问题 : 如果是引用类型(对象或者数组),那么返回值都是 Object,无法具体区分。
- 实例 :
var str = "hello world";
var num = 520;
var obj = new Object();
var arr = [1,2,3];
var fn = function(){
console.log("函数")
}
typeof(str) //string
typeof(num) //number
typeof(obj) //object
typeof(arr) //object
typeof(fn) //function
- 【 方法二 : instanceof 】
作用 :识别对象类型。判断一个对象是否属于某个构造函数的实例。
语法 : 变量名 instanceof 数据类型 || 实例对象名 instanceof 构造函数。
返回值 : boolean 值。
存在的问题 :只适用于对象类型,不适用于简单类型的数据类型。
- 实例 :
//1,只要是对象类型的都可以区分出来
arr instanceof Array //true
new Date() instanceof Date //true
//2,检验 F 是否属于构造函数 fn 的实例
var F = new fn(); //实例化构造函数
F instanceof fn ; //true,说明F是属于fn的实例
//3,对于不同的构造函数,同一个实例都返回 true,如下 F 对 Object 同样返回了 true
F instanceof Object //true
- 原理探究 :
instanceof 原理:
左边是一个实例对象,右边是一个构造函数,instanceof 会检查构造函数的原型对象 prototype 是否在左边对象的原型链上,有则返回 true,否则返回 false。
instanecof 内部执行函数
:instanceof (A,B) = { var L = A.__proto__; var R = B.prototype; if(L === R) { //A的内部属性__proto__指向B的原型对象 return true; } return false; } //左边对象的原型链以及右边函数的原型对象上都发生了什么? F.__proto__===fn.prototype //true 实例化对象F的原型指向fn的原型对象 F.__proto__.proto__||fn.prototype.__proto__===Object.prototype //true fn的原型又指向Object的原型对象 Object.prototype.__proto__ //null //说明从F——fn——Object都在一条原型链上,其中fn和Object的prototype属性都存在于F所在的这条 原型链上,所以,F针对于两个函数都返回了true
- 【 方法三 : constructor 】
作用 :判断数据类型,包括数组,日期,对象等,可以区分清楚。
语法 : 变量名.constructor === 数据结构。
返回值 : boolean 值。
描述 :判断所有的数据类型。本身是 prototype 对象的一个属性,默认指向 prototype 属性所在的构造函数,此处我们用来判断数据类型。
- 实例 :
str.constructor===String //true
num.constructor===Number //true
obj.constructor===Object //true
arr.constructor===Array //true
new Date().constructor===Date //true
- 【 方法四 :prototype 】
以上三种方法多少都会有一些不能判断的情况。为了保证兼容性,可以通过 Object.prototype.toString 方法,判断某个对象值属于哪种内置类型 (需要区分大小写)。
作用 :判断数据类型。
语法 : Object.prototype.toString.call(变量名)。
返回值 : 对应的数据类型。
描述 :判断某个对象值属于哪种内置类型 (需要区分大小写),判断所有的数据类型。
- 实例 :
Object.prototype.toString.call(“字符串”) === ‘[object String]’ //true;
Object.prototype.toString.call(123) === ‘[object Number]’ //true;
Object.prototype.toString.call([1,2,3]) === ‘[object Array]’ //true;
Object.prototype.toString.call(new Date()) === ‘[object Date]’ //true;
Object.prototype.toString.call(function a(){}) === ‘[object Function]’ //true;
Object.prototype.toString.call({}) === ‘[object Object]’ //true;
- 【 方法五 :jQuery.type() 】
作用 :判断数据类型,其判断结果显示都是小写字符串的形式。
语法 : jQuery.type(变量名)。
返回值 : 对应的数据类型。
描述 :jQuery.type() ---> 万能。判断所有的数据类型。
- 实例 :
//包括日期、正则、undefined、null等都是可以判断的
jQuery.type(str) //string
jQuery.type(num) //number
jQuery.type(arr) //array
jQuery.type(obj) //object
jQuery.type(fn) //funtion
jQuery.type(undefined) //undefined
jQuery.type(null) //null
jQuery.type() //undefined
jQuery.type(window.notDefined) //undefined