sky
sky

Reputation: 25

javascript function returning issue

I want to return the var "source" value for all the element, now when I put the "source" out of each function, it become undefined.I want to return the whole source array. How to do that? any help would be truly appreciated -

function _getSource(){
    var product = fpd.getProduct(true);

    $(product[0].elements).each(function(i, elem) {
        var source = elem.parameters['source'];
    })

    return source;
    alert (source);
}

Upvotes: 1

Views: 79

Answers (3)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324840

source is only defined inside the each function because you var'd it there.

Try this instead:

function _getSource() {
    return $(fpd.getProduct(true)[0].elements).map(function() {return this.parameters['source'];});
}

Upvotes: 0

Alnitak
Alnitak

Reputation: 340055

Assuming that you're actually after an array containing the source property of each element:

function _getSource(){
    var product = fpd.getProduct(true);

    return $(product[0].elements).map(function(i, elem) {
        return elem.parameters['source'];
    }).get();    // .get() turns jQuery collection into an array
}

.map is a very good replacement for a .each / push combo. It comes from functional languages where the "map" function just takes an array, transmutes each elements, and returns a new array of those transmuted results.

The final .get is not strictly necessary if you don't mind getting an array-like result back rather than a proper array.

Upvotes: 1

jbabey
jbabey

Reputation: 46657

When you write var source you are declaring a new variable scoped to the function of the each callback. Declare it outside and get rid of the var so you are just assigning instead of redeclaring, and you probably also want to build up an array and not just assign. Something like this:

function _getSource(){
    var product = fpd.getProduct(true);
    var sources = [];

    $(product[0].elements).each(function() {
        sources.push(elem.parameters['source']);
    })

    return sources;
}

Upvotes: 1

Related Questions