一、typeof 是一个一元运算符。检测数据类型,返回一个字符串,包含数据类型信息。例如:“number,string,undefined”
局限性:
1、typeof null ===》 “object”
2、typeof [] ===> "object"
不能具体检测对象数据类型的细分项(数组、正则...)
二、instanceof 检测某一个实例是否属于这个类
var ary = [1,2,3,4];
ary instanceof Array //如果true,说明ary是Array的一个实例,也就ary是一个数组。反之,返回false则不是一个数组。
ary.constructor == Array //通过constructor
局限性:
在关于类之间通过原型链的方式实现继承的时候,我们instanceof检测出来的结果不准确。例如:下面的代码:
function Fn(){} Fn.prototype = new Array; //Fn继承Array类 var f = new Fn(); console.log(f instanceof Array); //true console.log(f.constructor); //Array
console.log(f instanceof Object) //true
//实现真实的判断
function isArray(obj){
return Object.prototype.toString.call(obj) == "[Object Array]";
}
三、toString检测数据类型的原理:执行Object原型上的toString,让这个方法中的this变为我们要检测的那个值,就是实现数据类型的检测
//原理实现
Object.prototype.toString = function () { return "[object "+this.constructor+"]"; //左边数据类型,右边类名} var num = 1; console.log(Object.prototype.toString.call(num)); console.log({}.toString.call([]));
1、 null,undefeind上面的所有方法屏蔽了。所以不能使用toString方法。
1)经典错误:执行 undefined.toString();
Uncaught TypeError: Cannot read property 'toString' of undefined //这是undefind的错误,不能执行某个方法。
2)null和undefeind也是有类的:
Object.prototype.toString.call(null); //"[object Null]" Object.prototype.toString.call(undefined); //"[object Undefined]"
2、number上的toString
可以对数字的进制进行转换
var num = 25; num.toString(2); num.toString(8); num.toString(16); (25).toString(10); //如果是直接写函数,需要添加括号。表示这个值。 (0xff).toString(2); //可以各种进制间转换,比如16进制转2进制
3、toString判断DOM元素
//控制台下
document.toString() "[object HTMLDocument]" document.body.toString() "[object HTMLBodyElement]" div.toString() "[object HTMLParagraphElement]" p.toString() "[object HTMLParagraphElement]"
4、使用Object.prototype.toString实现严格判断数组
//instanceof不能精确判断数组所属的类
var ary = new Array(); console.log(ary instanceof Array); //true console.log(ary instanceof Object); //true
//另一个例子
function InheritArray(){}
InheritArray.prototype=new Array();
var fn = new InheritArray();
console.log(Object.prototype.toString(fn));