I'm trying to write a function that either accepts a list of strings, or a single string. If it's a string, then I want to convert it to an array with just the one item. Then I can loop over it without fear of an error.
So how do I check if the variable is an array?
I've rounded up the various solutions below and created a jsperf test.
You can try this:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray
There is a nice example in Stoyan Stefanov's book JavaScript Patterns which suppose to handle all possible problems as well as utilize ECMAScript 5 method Array.isArray().
So here it is:
By the way, if you are using jQuery, you can use it's method $.isArray()
Array.isArray works fast, but it isn't supported by all versions of browsers. So you could make an exception for others and use universal method:
This is my attempt to improve on this answer taking into account the comments:
It gets rid of the if/else, and accounts for the possibility of the array being null or undefined