js判断变量是不是数组的方法

方案一:instanceof

变量 instanceof 类型  返回的是布尔值  true false
例: var a = [] a instanceof Array

方案二:原型prototype + toString  call()

首先: Object.prototype.toString.call(variable)来判断,返回值是字符串
其次: Object.prototype.toString.call(variable).indexOf('Array') 如果变量对象是纯数组,返回的数字不是-1
最后: Object.prototype.toString.call(variable).indexOf('Array') !== -1 比对数值是否等于-1就能判断是否是数组类型 是为true

方案三:原型prototype + isPrototypeOf()

Array.prototype.isPrototypeOf(variable) 

isPrototypeOf() 函数 : 用于指示对象是否存在于一个对象的原型链中。如果存在返回true,反之返回false。该方法属Object对象,由于所有的对象都继承了Object的对象实例,因此几乎所有的实例对象都可以使用该方法。如果variable的原型链中存在Array对象,就会返回true,也就说明variable是数组类型。

方案四:构造函数 constructor

variable.constructor
variable.constructor.toString()
variable.constructor.toString().indexOf("Array") !== -1

一个数组类型的实例,其原型__proto__.constructor右边是Array关键字,再拿到字符串,最后查找字符串中Array关键字的位置是否等于-1

方案五:数组方法 isArray()

Array.isArray(variable)

 

posted @ 2018-11-20 14:53  倒霉催的  阅读(28438)  评论(0编辑  收藏  举报