https://stackoverflow.com/questions/767486/how-do-you-check-if-a-variable-is-an-array-in-javascript

1137down voteaccepted

There are several ways of checking if an variable is an array or not. The best solution is the one you have chosen.

variable.constructor === Array

This is the fastest method on Chrome, and most likely all other browsers. All arrays are objects, so checking the constructor property is a fast process for JavaScript engines.

If you are having issues with finding out if an objects property is an array, you must first check if the property is there.

variable.prop && variable.prop.constructor === Array

Some other ways are:

variable instanceof Array

This method runs about 1/3 the speed as the first example. Still pretty solid, looks cleaner, if you're all about pretty code and not so much on performance. Note that checking for numbers does not work as variable instanceof Number always returns falseUpdate: instanceof now goes 2/3 the speed!

Array.isArray(variable)

This last one is, in my opinion the ugliest, and it is one of the slowest. Running about 1/5 the speed as the first example. Array.prototype, is actually an array. you can read more about it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

So yet another update

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

This guy is the slowest for trying to check for an Array. However, this is a one stop shop for any type you're looking for. However, since you're looking for an array, just use the fastest method above.

Also, I ran some test: http://jsperf.com/instanceof-array-vs-array-isarray/33 So have some fun and check it out.

Note: @EscapeNetscape has created another test as jsperf.com is down. http://jsben.ch/#/QgYAV I wanted to make sure the original link stay for whenever jsperf comes back online.

最新文章

  1. ASP.NET Core和Angular 2双剑合璧
  2. IOS 解析crashlog
  3. jQuery动画特效笔记
  4. nohup命令
  5. unity3d 加密资源并缓存加载
  6. javaSE第三天
  7. 为Web Api 2认证服务器增加令牌刷新功能
  8. 如何让自己的电脑发布ASP http://jingyan.baidu.com/article/19192ad853224ce53f570748.html
  9. Json时间格式转换问题
  10. Android SectionIndexer 的使用(联系人分类索引)
  11. 将对象保存至文件——CArchive
  12. POJ 3047 Fibonacci
  13. poj 3266 Cow School 分数规划
  14. CoreJavaE10V1P3.7 第3章 Java的基本编程结构-3.7 输入输出(Input ,Output)
  15. 阿里云Linux挂载数据盘
  16. C++ CRTP singleton
  17. 在IIS中部署Asp.net Mvc
  18. yum仓库的定制
  19. linkin大话数据结构--泛型
  20. 分布式缓存Hazelcast案例一

热门文章

  1. 原生JS--各种兼容性写法总结
  2. react 的CDN 连接
  3. Vickers Vane Pump Tips - Vane Pump Maintenance Note
  4. PHP18 PHP与AJAX
  5. WebGL 绘制Line的bug(二)
  6. python 一些函数和类用法记录
  7. 第一讲:vcs simulation basic
  8. day17-python之文件操作
  9. UVa 12118 检查员的难题 (dfs判连通, 构造欧拉通路)
  10. Python利用flask sqlalchemy实现分页效果