3

假设我有一些 HTML 元素:

<div>First</div>
<div>Second</div>
<div>Third</div>

我通过以下方式选择的内容:

$('div').text();

如何对元素进行“foldl”操作(迭代、累积结果),例如使用换行符加入它们?

$('div').text().foldl('', function(){ ... join_or_whatever ... })
4

3 回答 3

5

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.

于 2011-06-13T17:45:52.560 回答
1

我不确定 foldl 是什么但是

这是您迭代和连接的方式:

var newArray = [];
//'div' is an outer container of your inner divs
$('div').each(function(index, Element) {
    newArray.push($(this).text());
});

$('body').append(newArray.join(''));
于 2011-06-13T17:41:55.440 回答
0

我想我明白你所说的“foldl”是什么意思,不确定......但试试这个:

var finalStr = "";
$('div').each(function(index) {
   finalStr += $(this).text() + "<br>";
});

可在:http ://api.jquery.com/each/

于 2011-06-13T17:53:34.050 回答