which is the best method used for checking isarray [duplicate]

匿名 (未验证) 提交于 2019-12-03 10:10:24

问题:

This question already has an answer here:

I want to check a variable is it array?

which is the best method used for this to get better performance.

isArray

or

instanceof

回答1:

Big guys (Jquery, underscore) do it like this:

  isArray = Array.isArray || function(obj) {     return Object.prototype.toString.call(obj) == '[object Array]';   }; 

But these are not the droids you're looking for you actually don't need this at all. Don't "check" your variables - just know them.



回答2:

Array.IsArray would be better to use.

Also check this instanceof considered harmful (or how to write a robust isArray)

The problems arise when it comes to scripting in multi-frame DOM environments. In a nutshell, Array objects created within one iframe do not share [[Prototype]]’s with arrays created within another iframe. Their constructors are different objects and so both instanceof and constructor checks fail:

Also you can check the speed variation between the two and you will find that isArray is comparatively faster.

Here is a link to check that:- Array.isArray vs instanceof Array

Below code is used to check the speed variation:

<script>   Benchmark.prototype.setup = function() {     var a = [1, 2, 3];     var s = 'example';     var f = false;   }; </script> 

Using Array.IsArray:

(Array.isArray(a) && (Array.isArray(s) || Array.isArray(f))); 

it performed nearly 25,255,693 ops/sec

Now using instanceof:-

 (a instanceof Array && (s instanceof Array || f instanceof Array)); 

it performed nearly 21,594,618 ops/sec

ie, instanceOf is 15% slower than using IsArray.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!