为大型列表优化 JQuery For Each Loop

Optimize a JQuery For Each Loop for large lists

我有一个 unordered list,其值高达 350。现在在 350 中,我想为 list6 值设置一个 css 属性。问题是我的 each 循环变得非常慢,因为我必须遍历每个 value。有什么方法或逻辑可以优化下面的每个循环。下面的代码。

$('ul.list.available li').each(function()
{
  if($(this)[0].innerText == 'Cat' || $(this)[0].innerText == 'Dog' || $(this)[0].innerText == 'Buffalo' ||
          $(this)[0].innerText == 'Ant' || $(this)[0].innerText == 'Rat' || $(this)[0].innerText == 'Mice' )
  {
         $(this)[0].style.display = 'none';
  }
});

您正在调用 $ 函数 7 次,一次就够了。此外,设置一个计数器来指示何时隐藏 6 也将节省大量迭代:

var counter = 0;

$('ul.list.available li').each(function() {
  var $this = $(this),
      text  = $this[0].innerText;

  if( text == 'Cat' || text == 'Dog' || text == 'Buffalo' || text == 'Ant' || text == 'Rat' || text == 'Mice' )
  {
    $this[0].style.display = 'none';
    counter++;
  } 

  if( counter == 6 )
  {
    return false;
  }
});

使用数组填充您的单词。你可以使用 jQuery 的 .filter() 方法和 JavaScript 的 Array.prototype.includes:

const words = ["Cat", "Dog", "Mice"]; // <<< populate this one!
$('ul.list.available li').filter((i, el) => words.includes(el.textContent)).hide();
<ul class="list available">
  <li>Bicycle</li>
  <li>Cat</li>
  <li>Boat</li>
  <li>Dog</li>
  <li>Mice</li>
  <li>Computer</li>
</ul>


<script src="//code.jquery.com/jquery-3.4.1.min.js"></script>

jQuery filter
MDN Array.prototype.includes

这类似于另一个答案,但允许您将数量(然后以 slice() 结束)和数组发送到一个函数,然后我添加一个 class - 这可能包括隐藏东西。因此,要将它们全部隐藏,只需将 0 传递给 hideSome(0, testfilters);。您也可以修改它以隐藏除最后 6 个以外的所有内容,您的问题和评论使您的意图有点 variable/unclear 因此这个答案。

function hideSome(howMany = 6, testArr) {
  let things = $('ul.list.available').find('li');
  let filteredThings = things.filter(function(index, element) {
   return testArr.includes(element.innerText);
  });
  filteredThings
    .slice(-howMany)
    .addClass("what-to");
}
let testfilters = ["Cat", "Dog", "Buffalo", "Ant", "Mice", "Rat"];

hideSome(6, testfilters);
.what-to {
  border: solid red 1px;
}
.found{color: blue;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<ul class="list available">
  <li>I am 0</li>
  <li>I am 1</li>
  <li>Rat</li>
  <li>rat</li>
  <li>I am 4</li>
  <li>Mice</li>
  <li>I am 6</li>
  <li>Ant</li>
  <li>I am 8</li>
  <li>mice</li>
  <li>Cat</li>
  <li>Chicken</li>
  <li>Hog</li>
  <li>I am 13</li>
  <li>Ant</li>
  <li>Pant</li>
  <li>Mice</li>
  <li>Buffalo</li>
  <li>Rat</li>
  <li>The end</li>
</ul>
<div id="indicator"></div>