plus-
plus-

Reputation: 46543

Jquery functional programming style

Is there a more elegant way to write this kind of function without having to initialize an array:

function getStuff () {
    var some_array= [];

    $("#some-id ul li span.key").each(function() {
          some_array.push($(this).text());
    });

    return some_array;
}

Upvotes: 3

Views: 3978

Answers (2)

Fabrício Matté
Fabrício Matté

Reputation: 70199

jQuery.map

function getStuff () {
    return $.map($("#some-id ul li span.key"), function(el) {
          return $(el).text();
    });
}

Fiddle

Performance-wise, the difference is minimal. Also, as noted by Lix, choose the method which you find more readable and maintainable. In the end, both will end up creating an array, iterating over elements, pushing string values to the array and returning the array.

Upvotes: 9

Stephen
Stephen

Reputation: 5770

Just another more functional feeling way to go about this might be:

Define a "method" function:

var method = function (method) {
    return function (item) {
        return $(item)[method]();
    };
};

You can use it like this:

var text = method('text');
var html = method('html');
var fadeIn = method('fadeIn');

To re-work your getStuff function:

var getText = function (arr) {
    return $.map(arr, text);
};

$.map iterates through the array that was passed in, applying the function that was returned from var text = method('text'), which is just the execution of $(array item).method().

I just threw this together to demonstrate a way you can use these kinds of techniques. You would probably name things differently and define the "method" function as a custom library/helper that is meant to be used app-wide.

Upvotes: 5

Related Questions