本文介绍了在数据表中使用正则表达式获取元素的唯一值计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据表,其结构如下:
I have a data table that has a structure like:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>ABC</td>
<td></td>
<td id="invNumbers0">12345</td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<td>GHI</td>
<td></td>
<td id="invNumbers1">12345</td>
<td></td>
</tr>
<tr>
<td>MNO</td>
<td></td>
<td id="invNumbers2">4566</td>
<td></td>
</tr>
<tr>
<td>STU</td>
<td></td>
<td id="invNumbers3">12345</td>
<td></td>
</tr>
<tr>
<td>ABC</td>
<td></td>
<td id="invNumbers4">2566</td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<td>GHI</td>
<td></td>
<td id="invNumbers5">4566"</td>
<td></td>
</tr>
<tr>
<td>MNO</td>
<td></td>
<td id="invNumbers6">12345</td>
<td></td>
</tr>
<tr>
<td>STU</td>
<td></td>
<td id="invNumbers7">12345</td>
<td></td>
</tr>
</tbody>
</table>
我想对ID以 invNumbers开头的元素中存在的唯一值进行计数。
重复值仅应计算一次。因此,这里的输出应为
Count = 3。由于我只有3个唯一值,即12345,4566,2566。
I want to have the count of the unique values present in the elements with id starting from "invNumbers".Duplicate values should be only counted once. So here the output should beCount = 3 . As I have only 3 unique values i.e. 12345,4566,2566.
推荐答案
这里有3个版本
- 带有粗箭头的ES6
- 具有功能的ES2015
- 传统版JS,应从IE8左右运行
const uniqueCount = [...document.querySelectorAll("td[id^=invNumbers]")]
.reduce((acc, cur) => {
const val = cur.textContent;
if (!acc.includes(val)) acc.push(val);
return acc;
}, []).length;
console.log(uniqueCount)
// no fat arrows =>
const uniqueCount1 = [...document.querySelectorAll("td[id^=invNumbers]")]
.reduce(function(acc, cur) {
const val = cur.textContent;
if (!acc.includes(val)) acc.push(val);
return acc;
}, []).length;
console.log(uniqueCount1)
// Legacy - not ES2015 or ES6
var cells = document.querySelectorAll("td[id^=invNumbers]"); // supported since IE9 or so
var arr = [];
for (var i = 0; i < cells.length; i++) {
var val = cells[i].innerText;
if (arr.indexOf(val) ===-1) arr.push(val);
}
console.log(arr.length)
<table>
<tbody>
<tr>
<td>ABC</td>
<td></td>
<td id="invNumbers0">12345</td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<td>GHI</td>
<td></td>
<td id="invNumbers1">12345</td>
<td></td>
</tr>
<tr>
<td>MNO</td>
<td></td>
<td id="invNumbers2">4566</td>
<td></td>
</tr>
<tr>
<td>STU</td>
<td></td>
<td id="invNumbers3">12345</td>
<td></td>
</tr>
<tr>
<td>ABC</td>
<td></td>
<td id="invNumbers4">2566</td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<td>GHI</td>
<td></td>
<td id="invNumbers5">4566</td>
<td></td>
</tr>
<tr>
<td>MNO</td>
<td></td>
<td id="invNumbers6">12345</td>
<td></td>
</tr>
<tr>
<td>STU</td>
<td></td>
<td id="invNumbers7">12345</td>
<td></td>
</tr>
</tbody>
</table>
这篇关于在数据表中使用正则表达式获取元素的唯一值计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!