如何反向循环cheerio对象?

时间:2018-05-09 02:42:10

标签: javascript cheerio

https://github.com/cheeriojs/cheerio

让我们保存一个我有一长串元素(1000+),我想要反过来循环。最有效的方法是什么?感谢

$('li').each(function(i, elem) {
  fruits[i] = $(this).text();
});

2 个答案:

答案 0 :(得分:1)

How about a for loop?

const li = $('li');

for (let i = li.length - 1; i >= 0; i--) {
  $(li[i]).text();
}

答案 1 :(得分:0)

One way would be to use $('li').size() - 1 - i as the index:

const fruits = [];

$('li').each(function(i, elem) {
  fruits[$('li').size() - 1 - i] = $(this).text();
});

console.log(fruits);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<li>Apple</li>
<li>Banana</li>
<li>Pear</li>