Skip to content

Commit 6f83d46

Browse files
committed
Merge pull request #58 from amsul/master
added recipe for checking type of value is array
2 parents e993e45 + 3f2895a commit 6f83d46

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
---
2+
layout: recipe
3+
title: Check if type of value is an Array
4+
chapter: Arrays
5+
---
6+
## Problem
7+
8+
You want to check if a value is an `Array`.
9+
10+
{% highlight coffeescript %}
11+
myArray = []
12+
console.log typeof myArray // outputs 'object'
13+
{% endhighlight %}
14+
15+
The `typeof` operator gives a faulty output for arrays.
16+
17+
## Solution
18+
19+
Use the following code:
20+
21+
{% highlight coffeescript %}
22+
typeIsArray = Array.isArray || ( value ) -> return {}.toString.call( value ) is '[object Array]'
23+
{% endhighlight %}
24+
25+
To use this, just call `typeIsArray` as such:
26+
27+
{% highlight coffeescript %}
28+
myArray = []
29+
typeIsArray myArray // outputs true
30+
{% endhighlight %}
31+
32+
## Discussion
33+
34+
The method above has been adopted from "the Miller Device". An alternative is to use Douglas Crockford's snippet:
35+
36+
{% highlight coffeescript %}
37+
typeIsArray = ( value ) ->
38+
value and
39+
typeof value is 'object' and
40+
value instanceof Array and
41+
typeof value.length is 'number' and
42+
typeof value.splice is 'function' and
43+
not ( value.propertyIsEnumerable 'length' )
44+
{% endhighlight %}

0 commit comments

Comments
 (0)