Javascript: N种方法判断一个变量是不是数组

Array.isArray()

IE9+,很是广泛的用法,好比{a: '1'},Array.isArray({a: '1'})返回false数组

variable.constructor === Array

变量是由Array构造函数生成的数组,寻找变量的构造函数...函数

[1,2,3] instanceof Array

返回一个布尔值,顺便提一下,instanceof这个方法判断基本数据类型是会失效的,好比 1 instanceof Number为假,'2' instanceof String为假,可是若是这样处理:测试

const a = new Number(2);
a instanceof Number     // true
复制代码

随便找一个数组仅有的方法

可能有人有疑问,2..sort或者'2'.sort会不会报错,实际上是不会的,可是ture.sort会不起反应,因此最优的作法是:spa

typeof variable === 'object' && variable.sort === Array.prototype.sort
复制代码

Object.prototype.toString.call(variable) === '[object Array]'

基本全支持,这个是惯常的用法,很是准确prototype

Object.getPrototypeOf(variable) === Array.prototype

IE9+,这也是个方法,可是须要注意,在 ES5 中,若是参数不是一个对象类型,将抛出一个TypeError异常。在 ES2015 中,参数会被强制转换为一个 Object:code

Object.getPrototypeOf('foo');
// TypeError: "foo" is not an object (ES5 code)
Object.getPrototypeOf('foo');
// String.prototype                  (ES2015 code)
复制代码

Array.prototype.isPrototypeOf(variable)

这样真的能够,并且基本全支持,Object.isPrototypeOf() 方法用于测试一个对象是否存在于另外一个对象的原型链上。对象

相关文章
相关标签/搜索