How to return an array of values ​​from an evaluation method

I am using casper.evaluate () to get an array of data from this page. However, it doesn't seem to be returning an array (whereas the returning strings work flawlessly). What could be the problem?

To clarify: the code in the assessment:

function(){ 
    return $('#id a').map(function(i, e) { 
        return $(e).attr('href'); 
    }).get(); 
}

      

.get()

at the end of the call is to get an array instead of a jQuery object. BTW, I'm pretty sure jQuery is available on the page.

+3


source to share


3 answers


You don't need jQuery here:



casper.evaluate(function() {
    return [].map.call(__utils__.findAll('#id a'), function(node) {
        return node.getAttribute('href');
    });
});

      

+3


source


I believe .get () is irrelevant.

Returning without .get () creates a very nice array, have a look at this jsfiddle example http://jsfiddle.net/YFsRw/



r = function(){ 
    return $('#id a').map(function(i, e) { 
        return $(e).attr('href'); 
    }); 
}

var p = r();

// p servers as a nice array :)
for (i = 0; i < p.length; i++) {
    document.write(p[i] + "<br/>");
}

      

0


source


.toArray () is what you are looking for.

.toArray () [Returns: Array]

Description: Retrieve all the elements contained in the jQuery set as an array.

function(){ 
    return $('#id a').map(function(i, e) { 
        return $(e).attr('href'); 
    }).toArray(); 
}

      


Alternatively, there is also one $.makeArray()

that works at a broader level, more than just jQuery, and is called statically.

function(){ 
    return $.makeArray(
        $('#id a').map(function(i, e) { 
            return $(e).attr('href'); 
        })
    ); 
}

      

(But it seems more appropriate and understandable in this case.) .toArray()


See this SO answer for a comparison of the two.

0


source







All Articles