1

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);
}
0

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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;
}

2 Comments

he has no "outer source variable". And why not use .map - it's designed for exactly this.
@Alnitak thanks, assumed there was an outer source. I agree that looping with each and calling push is not as elegant as map, but as the OP is admittedly beginner it may be better to take small steps
0

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'];});
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.