Say I have some HTML elements:
<div>First</div>
<div>Second</div>
<div>Third</div>
Whose content I select via a:
$('div').text();
How can I make a "foldl" operation on the elements 开发者_C百科(iterate, accumulating a result), for example to join them using a newline?
$('div').text().foldl('', function(){ ... join_or_whatever ... })
According to the Wikipedia article on folding, JavaScript's Array.reduce() (for foldl) and Array.reduceRight() (for foldr) functions provide array folding.
So your specific task becomes:
var result = $.makeArray($('div')).reduce(function(prev,curr){
return prev + '\n' + $(curr).text()
});
Note that not all implementations of JavaScript support reduce and reduceRight, so see this example implementation if needed.
UPDATED: Since jQuery doesn't return a true array for $(selector) and some platforms do not support reduce and reduceRight on jQuery's "array-like" collection, I've updated the answer to use $.makeArray() as suggested below. Thanks to @royas for the catch.
I'm not sure what foldl is but
here's how you iterate and concatenate:
var newArray = [];
//'div' is an outer container of your inner divs
$('div').each(function(index, Element) {
newArray.push($(this).text());
});
$('body').append(newArray.join(''));
I think I understand what you mean by "foldl", not sure... But try this:
var finalStr = "";
$('div').each(function(index) {
finalStr += $(this).text() + "<br>";
});
Available at: http://api.jquery.com/each/
精彩评论