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?
Source: Tips4all, CCNA FINAL EXAM
The method given in the ECMAScript standard to find the class of Object is to use the toString method from Object.prototype.
ReplyDeleteif( Object.prototype.toString.call( someVar ) === '[object Array]' ) {
alert( 'Array!' );
}
Or you could use typeof to test if it is a String:
if( typeof someVar === 'string' ) {
someVar = [ someVar ];
}
Or if you're not concerned about performance, you could just do a concat to a new empty Array.
someVar = [].concat( someVar );
EDIT: Check out a thorough treatment from @T.J. Crowder's blog, as posted in his comment below.
I would first check if your implementation supports isArray:
ReplyDeleteif (Array.isArray)
return Array.isArray(v);
You could also try using the instanceof operator
v instanceof Array
jQuery also offers an isArray method:
ReplyDeletevar a = ["A", "AA", "AAA"];
if($.isArray(a)) {
alert("a is an array!");
} else {
alert("a is not an array!");
}
You can try this approach: http://www.ajaxdr.com/code/javascript-version-of-phps-is_array-function/
ReplyDeleteEDIT: also, if you are already using JQuery in your project, you can use its function $.isArray().
If the only two kinds of values that could be passed to this function are a string or an array of strings, keep it simple and use a typeof check for the string possibility:
ReplyDeletefunction someFunc(arg) {
var arr = (typeof arg == "string") ? [arg] : arg;
}
The best solution I've seen is a cross-browser replacement for typeof. Check Angus Croll's solution here.
ReplyDeleteThe TL;DR version is below, but the article is a great discussion of the issue so you should read it if you have time.
Object.toType = function(obj) {
return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
}
// ... and usage:
Object.toType([1,2,3]); //"array" (all browsers)
// or to test...
var shouldBeAnArray = [1,2,3];
if(Object.toType(shouldBeAnArray) === 'array'){/* do stuff */};
I know, that people are looking for some kind of raw javascript approach.
ReplyDeleteBut if you want think less about, take a look here: http://documentcloud.github.com/underscore/#isArray
isArray_.isArray(object)
Returns true if object is an Array.
(function(){ return _.isArray(arguments); })();
=> false
_.isArray([1,2,3]);
=> true
You could try checking if the object in question has an array method as one of its methods such as push or slice. This doesn't guarantee absolutely that it is an array, but objects that have methods with those names are probably going to be arrays.
ReplyDeletevar a = [];
var b = {};
if ((a.slice) && (a.slice === function))
{
alert ('A is an array');
}
else
{
alert ('A is not an array');
}
if ((b.slice) && (b.slice === function))
{
alert ('B is an array');
}
else
{
alert ('B is not an array');
}
Beware, however, this method can be defeated if you have a non-array object that happens to implement a slice methods.
b.slice = function (){}
if ((b.slice) && (b.slice === function))
{
alert ('B is an array');
}
else
{
alert ('B is not an array');
}