Navigation Menu

Skip to content

Commit

Permalink
Merge pull request #58 from amsul/master
Browse files Browse the repository at this point in the history
added recipe for checking type of value is array
  • Loading branch information
amsul committed Sep 13, 2012
2 parents e993e45 + 3f2895a commit 6f83d46
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions chapters/arrays/check-type-is-array.md
@@ -0,0 +1,44 @@
---
layout: recipe
title: Check if type of value is an Array
chapter: Arrays
---
## Problem

You want to check if a value is an `Array`.

{% highlight coffeescript %}
myArray = []
console.log typeof myArray // outputs 'object'
{% endhighlight %}

The `typeof` operator gives a faulty output for arrays.

## Solution

Use the following code:

{% highlight coffeescript %}
typeIsArray = Array.isArray || ( value ) -> return {}.toString.call( value ) is '[object Array]'
{% endhighlight %}

To use this, just call `typeIsArray` as such:

{% highlight coffeescript %}
myArray = []
typeIsArray myArray // outputs true
{% endhighlight %}

## Discussion

The method above has been adopted from "the Miller Device". An alternative is to use Douglas Crockford's snippet:

{% highlight coffeescript %}
typeIsArray = ( value ) ->
value and
typeof value is 'object' and
value instanceof Array and
typeof value.length is 'number' and
typeof value.splice is 'function' and
not ( value.propertyIsEnumerable 'length' )
{% endhighlight %}

0 comments on commit 6f83d46

Please sign in to comment.