File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 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 %}
You can’t perform that action at this time.
0 commit comments