How do you check if a variable is an array in JavaScript? [duplicate]
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.
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.
Some other ways are:
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
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
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. |
最新文章
- ASP.NET Core和Angular 2双剑合璧
- IOS 解析crashlog
- jQuery动画特效笔记
- nohup命令
- unity3d 加密资源并缓存加载
- javaSE第三天
- 为Web Api 2认证服务器增加令牌刷新功能
- 如何让自己的电脑发布ASP http://jingyan.baidu.com/article/19192ad853224ce53f570748.html
- Json时间格式转换问题
- Android SectionIndexer 的使用(联系人分类索引)
- 将对象保存至文件——CArchive
- POJ 3047 Fibonacci
- poj 3266 Cow School 分数规划
- CoreJavaE10V1P3.7 第3章 Java的基本编程结构-3.7 输入输出(Input ,Output)
- 阿里云Linux挂载数据盘
- C++ CRTP singleton
- 在IIS中部署Asp.net Mvc
- yum仓库的定制
- linkin大话数据结构--泛型
- 分布式缓存Hazelcast案例一