1、instanceof
let a = [];
a instanceof Array; //true
instanceof运算符检测Array.prototype属性是否存在于变量a的原型链上.。
存在问题:
- prototype属性是可以修改的,所以并不是最初判断为true就一定永远为真
- 当我们的脚本拥有多个全局环境,例如html中拥有多个iframe对象,不同的全局环境会拥有自己的
Array.prototype
属性,Array.prototype !== window.frames[0].Array.prototype
2、constructor
let a = [];
a.constructor === Array // true
存在问题:
这种判断也会存在多个全局环境的问题,导致的问题与instanceof相同。
3、Object.prototype.toString.call()
Object.prototype.toString().call()
可以获取到对象的不同类型,例如:
let a = [1,2,3]
Object.prototype.toString.call(a) === '[object Array]';//true
//检验是否是函数
let a = function () {};
Object.prototype.toString.call(a) === '[object Function]';//true
//检验是否是数字
let b = 1;
Object.prototype.toString.call(a) === '[object Number]';//true
甚至对于多全局环境时, Object.prototype.toString().call()
也能符合预期处理判断。
4、Array.isArray() (最推荐)
let a = [1, 2, 3]
Array.isArray(a) // true;