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.
source to share
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/>");
}
source to share
.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.
source to share