jQuery.each for lists and non-lists

Posted by Brian M. Hunt on Stack Overflow See other posts from Stack Overflow or by Brian M. Hunt
Published on 2010-06-13T02:42:47Z Indexed on 2010/06/13 2:52 UTC
Read the original article Hit count: 420

Filed under:
|

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

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery