Now that I'm programming in javascript more and more often, there's a task I'm coming across quite often that I wonder could be dealt with more elegantly.
It's about checking whether a variable, values
say, is an array of Xs, or rather just an X, immediatly followed by an iteration over it or its elements.
(X being object, string, number, ... anything really -- except array).
Especially when dealing with xml or json files, a single X is not wrapped in [ ] to make it a 1-element array, and my code breaks if I don't watch out.
I deal with this now in the following way:
if (!(values instanceof Array)) values = [values]
values.forEach(function(value){/*do stuff with value*/});
For now, I've written a function to take care of this,
function arrayIfNot(arr) {return (arr instanceof Array) ? arr : [arr];}
Which I can use as
arrayIfNot(values).forEach(function(value){/*do stuff with value*/});
but as it is such a common task, I'd be surprised if there isn't a common shortcut or library function (jQuery?) to do this.
Thanks!
EDIT:
I suppose I could extend the prototypes like so (haven't tried):
Array.prototype.toArray = function () {return this;};
String.prototype.toArray = function () {return [this];};
...
so that I could do
values.toArray().forEach(function(value){/*do stuff with value*/});
but I'm always warned against extending the prototype. What do you think?
Thanks again!