jQuery 切片负索引不起作用

jQuery slice negative index not working

我遇到了一个奇怪的问题,可能是我遗漏了什么。

我得到了一个元素列表,其中一部分是可见的,另一部分是不可见的。

我要select不可见部分的最后3个元素。 我添加了一个片段来说明这个问题。

我要找的结果是 10, 11, 12 显示在 js 运行 之后,而不是 1,2,3 我以为 slice(-3) 会给我数组的最后 3 个元素,但似乎我遗漏了什么。当我使用 filter(':gt(-4)') 时会发生同样的问题。 有人可以解释一下我做错了什么吗?

jQuery(document).ready(function() {
  setTimeout(function () {
    var prevs = jQuery('li').filter(':visible').first().prevAll();
    var vis = jQuery('li').filter(':visible');
    
    vis.hide(1000);
    prevs.slice(-3).show(1000);
    
  }, 1000);
});
li:nth-last-child(n+4) {
  display: none
}

li {
  width: 30px;
  height: 30px;
  border: 1px dotted gray;
  background-color: red;
  list-style: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>
  <li>11</li>
  <li>12</li>
  <li>13</li>
  <li>14</li>
  <li>15</li>
</ul>

问题是 var prevs = jQuery('li').filter(':visible').first().prevAll();,具体来说,是 prevAll()。每 jquery documentation:

The .prevAll() method searches through the predecessors of these elements in the DOM tree and construct a new jQuery object from the matching elements; the elements are returned in order beginning with the closest sibling.

你得到的数组是0-11的元素,只是顺序相反。所以prevs[0] == 12。最后 3 个元素现在是 1、2 和 3。要解决此问题,您需要反转数组。只需将右边的语句包裹在 Array.prototype.reverse.call() 中。这就是你想要的我相信

jQuery(document).ready(function() {
  setTimeout(function () {
    var prevs = Array.prototype.reverse.call(jQuery('li').filter(':visible').first().prevAll());
    var vis = jQuery('li').filter(':visible');
    
    vis.hide(1000);
    prevs.slice(-3).show(1000);
    
  }, 1000);
});
li:nth-last-child(n+4) {
  display: none
}

li {
  width: 30px;
  height: 30px;
  border: 1px dotted gray;
  background-color: red;
  list-style: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>
  <li>11</li>
  <li>12</li>
  <li>13</li>
  <li>14</li>
  <li>15</li>
</ul>