js判断数组的方法及对比
主要有三个:Object.prototype.toString.call() 、 instanceof 以及 Array.isArray(),对比如下:
- Object.prototype.toString.call()
- 优点:这种方法对于所有基本的数据类型都能进行判断,即使是 null 和 undefined 。
- 缺点:不能精准判断自定义对象,对于自定义对象只会返回[object Object]
- instanceOf
- 优点:instanceof 可以弥补 Object.prototype.toString.call()不能判断自定义实例化对象的缺点。
- 缺点: instanceof 只能用来判断对象类型,原始类型不可以。并且所有对象类型 instanceof Object 都是 true,且不同于其他两种方法的是它不能检测出 iframes。
- Array.isArray()
- 优点:当检测 Array 实例时,Array.isArray 优于 instanceof ,因为 Array.isArray 可以检测出 iframes
- 缺点:只能判别数组

浙公网安备 33010602011771号