基本类型与引用类型
基本类型:number、string、boolean、undefined、null、 引用类型:object(包括array/function)根据JS的语法,要满足===的条件如下:
如果是引用类型,则两个变量必须指向同一个对象(同一个地址);如果是基本类型,则两个变量除了类型必须相同外,值还必须相等。判断类型
一.判断数组 1、typeoftypeof Null = 'object'; typeof Undefined = 'undefined'; typeof Function = 'function'; typeof Array = 'object'; typeof Object = 'object'; 12345 2、instanceof
instanceof运算符可以用来判断某个构造函数的prototype属性所指向的對象是否存在于另外一个要检测对象的原型链上。
array instanceof Array = true; array instanceof Object = true; object instanceof Object = true; object instanceof Array = false; 1234 3、constructor
实例化的数组拥有一个constructor属性,这个属性指向生成这个数组的方法。虽然可以用constructor判断是不是数组,但是极其容易改写了constructor。
array.constructor = 'function Array(){ [native code] }'; object.constructor = 'function Object(){ [native code] }'; 12 4、Object.toString()
使用Object.prototype.toString方法来判断,每一个继承自Object的对象都拥有toString的方法。如果一个对象的toString方法没有被改写过,那么toString方法会返回’[object type]’。
Object.toString()方法不能用,比如:
['hello'].toString = 'hello'; 'hello'.toString = 'hello'; {"a": 'hello'}.toString = '[object Object]' 123
array/object/string等的prototype都是object,所以他们的prototype都有toString这个方法。
Object.prototype.toString.apply(array) == '[object Array]'; Object.prototype.toString.apply(object) == '[object Object]'; Object.prototype.toString.apply(string) == '[object String]'; 123
apply和call都可以用来改变toString的执行上下文。
使用Object.prototype.toString来判断是否是数组的前提是不能重写toString方法。
isArray是ES6中的新方法,不管怎样改变toString或者constructor都可以正常使用。
Array.isArray(array) = true; 1
最终方法
if(!Array.isArray){ Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; } } 12345
