Skip to content

added recipe for checking type of value is array #58

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 13, 2012
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
added recipe for checking type of value is array
  • Loading branch information
amsul committed Sep 13, 2012
commit 3f2895a6e5bb2d32599fc4aeb34b066a7bb08939
44 changes: 44 additions & 0 deletions chapters/arrays/check-type-is-array.md
Original file line number Diff line number Diff line change
@@ -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 %}