判断数据类型
1. typeof
-
对于基本类型,除
null
以外,均可以返回正确的结果。 -
对于引用类型,除
function
以外,一律返回object
类型。 -
对于
null
,返回object
类型。 -
对于
function
返回function
类型。 -
typeof (123)//"number" typeof ("123")//"string" typeof ([1,2])//"object" typeof (null)//"object" typeof (function func(){}//"function" typeof Symbol()//"symbol" typeof new Date(); //object 无效 typeof new RegExp(); //object 无效
2. instanceof
-
用来判断A是否为B的实例:
A instanceof B
-
instanceof
检测的是原型 -
instanceof
只能用来判断两个对象是否属于实例关系, 而不能判断一个对象实例具体属于哪种类型。因果关系 o3.__proto__ === M.prototype o3 instanceof M //true M.prototype._proto_ === Object.prototype //针对M来说 o3 instanceof Object //true
-
instanceof
无法检测基本数据类型; -
[] instanceof Array; //true {} instanceof Object;//true new Date() instanceof Date;//true new RegExp() instanceof RegExp//true null instanceof Null//报错 undefined instanceof undefined//报错
3. toString
是object的原型方法
-
let arr = [1,2,3]; const func = function(){}; var data = new Date(); var string = "xuting" ; var number = 2; var nul = null; var und = undefined; var obj = { A:1, B:2 } console.log(Object.prototype.toString.call(arr));//"[object Array]" console.log(Object.prototype.toString.call(data));//"[object Date]" console.log(Object.prototype.toString.call(func));//"[object Function]" console.log(Object.prototype.toString.call(string));//"[object String]" console.log(Object.prototype.toString.call(obj));//"[object Object]" console.log(Object.prototype.toString.call(number));//"[object Number]" console.log(Object.prototype.toString.call(nul));//"[object Null]" console.log(Object.prototype.toString.call(und));//"[object Undefined]"
问题:那么为什么不使用数据类型自己本身的
toString()
方法呢
- 因为所有类在继承Object方法时,会改写toString()方法
-
var arr = [1,2,3] console.log(arr.toString());//'1,2,3' console.log(Array.prototype.toString);//'1,2,3' delete Array.prototype.toString;//删除Array原型上的toString()方法 //就会向上层访问这个方法,即Object的toString()方法 console.log(arr.toString());//'[object Array]'
4. constructor
-
当一个函数 F被定义时,JS引擎会为F添加
prototype
原型,然后再在prototype
上添加一个constructor
属性,并让其指向 F 的引用 -
function b(){console.log(1)}; b.prototype.constructor === b; // true (123).constructor //Number(){}