views:

49

answers:

2

I've a jQuery.each(data, foo), where data is either a string or a list of strings. I'd like to know if there's an existing utility function to convert the string to a list, or otherwise perform foo on just the string. So instead of the easy route:

if (!$.isArray(data)) {
  foo(0, data); // can't rely on `this` variable
} else {
  $.each(data,foo);
}

I was just wondering if there was already a builtin function of jQuery or Javascript that would convert data to a list automatically, like this:

function convert_to_list(data) { return $.isArray(data) ? data : [data]; }

$.each(convert_to_list(data), foo);

Just curious!

Thanks for reading.

Brian

+2  A: 

Rather than converting to an array, you could "bind" the string to foo using .apply() or .call():

if (!$.isArray(data)) {
  foo.call(data, 0); // `this` will point to data
} else {
  $.each(data,foo);
}
Andy E
+1  A: 

Andy's approach is a good one. Alternatively, you can always force data to be an array and then feed to jQuery.each

if(typeof data == 'string') {
    data = [data];
}
jQuery.each(data, foo);

Another option is to always wrap the input in an array regardless of it's type (string or array), and then flatten it. flatten, as the name suggests, will flatten multi-level arrays to a single level. So [["foo", "bar"]] becomes ["foo", "bar"]. The code them becomes:

jQuery.each([data].flatten(), foo);

Various libraries provide the flatten method, and a pure JavaScript implementation can be found here and another example at MDC that only flattens arrays two levels deep.

Anurag