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 so
Imagine you have this array below:
var arr = [1,2,3,4,5];
Javascript (new and older browsers):
function isArray(arr) {
return arr.constructor.toString().indexOf("Array") > -1;
}
or
function isArray(arr) {
return arr instanceof Array;
}
or
function isArray(arr) {
return Object.prototype.toString.call(arr) === '[object Array]';
}
then call it like this:
isArray(arr);
Javascript (IE9+, Ch5+, FF4+, Saf5+, Opera10.5+)
Array.isArray(arr);
jQuery:
$.isArray(arr);
Angular:
angular.isArray(arr);
Underscore and Lodash:
_.isArray(arr);
You could is isArray method but I would prefer to check with
Object.getPrototypeOf(yourvariable) === Array.prototype
You can check the type of your variable whether it is an array with;
var myArray=[];
if(myArray instanceof Array)
{
....
}
A = [1,2,3]
console.log(A.map==[].map)
In search for shortest version here is what I got so far.
Note, there is no perfect function that will always detect all possible combinations. It is better to know all abilities and limitations of your tools than expect a magic tool.
I would first check if your implementation supports isArray
:
if (Array.isArray)
return Array.isArray(v);
You could also try using the instanceof
operator
v instanceof Array
I would make a function to test the type of object you are dealing with...
function whatAmI(me){ return Object.prototype.toString.call(me).split(/\W/)[2]; }
// tests
console.log(
whatAmI(["aiming","@"]),
whatAmI({living:4,breathing:4}),
whatAmI(function(ing){ return ing+" to the global window" }),
whatAmI("going to do with you?")
);
// output: Array Object Function String
then you can write a simple if statement...
if(whatAmI(myVar) === "Array"){
// do array stuff
} else { // could also check `if(whatAmI(myVar) === "String")` here to be sure
// do string stuff
}