I would like to check whether a variable is either an array or a single value in JavaScript.
I have found a possible solution...
if (variable.constructor == Array)...
Is this the best way this can be done?
I would like to check whether a variable is either an array or a single value in JavaScript. I have found a possible solution...
Is this the best way this can be done? |
|||||||||||||
|
You could also use:
This seems to me a pretty elegant solution, but to each his own. |
|||||||||||
|
If you're only dealing with EcmaScript 5 and above then you can use the built in e.g.,
|
|||
|
I liked the Brian answer:
but you could just do like this:
|
|||
|
|
|||
|
I was using this line of code:
|
|||
|
I noticed someone mentioned jQuery, but I didn't know there was an jQuery implements it as Peter suggests:
Having put a lot of faith in jQuery already (especially their techniques for cross-browser compatibility) I will either upgrade to version 1.3 and use their function (providing that upgrading doesn’t cause too many problems) or use this suggested method directly in my code. Many thanks for the suggestions. |
||||
|
There are multiple solutions with all their on quirks. This page gives a good overview. One possible solution is:
|
|||||||||||||||||
|
I personally like Peter's suggestion: http://stackoverflow.com/a/767499/414784 (for ECMAScript 3. For ECMAScript 5, use Comments on the post indicate, however, that if
Note that in JavaScript The Definitive Guide 6th edition, 7.10, it says |
||||
|
Thought I would add another option for those who might already be using the Underscore.js library in their script. Underscore.js has an isArray() function (see http://documentcloud.github.com/underscore/#isArray).
|
||||
|
This is an old question but having the same problem i found a very elegant solution that i want to share. Adding a prototype to Array makes it very simple
Now once if you have an object you want to test to see if its an array all you need is to check for the new property
isArray is only available if its an array |
|||||||||||||||||||
|
When I posted this question the version of JQuery that I was using didn't include an Since JQuery now does offer this function, I would always use it...
(as of version 1.6.2) It is still implemented using comparisons on strings in the form
|
|||
|
code referred from https://github.com/miksago/Evan.js/blob/master/src/evan.js
|
||||
|
Via Crockford:
The main failing Crockford mentions is an inability to correctly determine arrays that were created in a different context, e.g., |
|||
|