【问题标题】:filter objects but return index and not object itself过滤对象但返回索引而不是对象本身
【发布时间】:2021-06-29 17:53:57
【问题描述】:
我想过滤分配了特定类的对象。我需要它们的索引位置。这是我的js代码:
arr = $('table td').filter('.class', function() {
return $(this).index()
});
console.log(arr);
这将返回所有分配了 .class 类的 tds。但我想有他们的索引位置。我怎样才能做到这一点?我也尝试使用 grep 来解决这个问题。同样的问题。
【问题讨论】:
标签:
javascript
jquery
filter
filtering
【解决方案1】:
使用map() 根据从匹配元素派生的值返回一个新数组
const arr = $('table td.class').map((i, el) => $(el).index()).get()
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="class"></td>
<td></td>
<td></td>
<td class="class"></td>
<td></td>
</tr>
</table>
【解决方案2】:
我认为解决此问题的方法是使用通用迭代方法,并在找到此类元素时将索引推送到数组:
const arr = [];
$('table td').each(function(i) {
if (this.matches('.class')) {
arr.push(i);
}
});
不需要像 jQuery 这样的大型库来处理这么琐碎的事情:
const arr = [];
const tds = document.querySelectorAll('table td');
for (let i = 0; i < tds.length; i++) {
if (tds[i].matches('.class')) {
arr.push(i);
}
}