【发布时间】:2014-05-18 17:40:19
【问题描述】:
有没有一种方法可以使用 jQuery / JS 创建一个包含表中所有唯一值的数组,即没有重复值?
此外,我感兴趣的值仅在具有特定类 (myClass) 的 TD 中 + 我想将“”和“”排除为无效值。
在以下示例中,输出应为 [item1,item2,item3] 作为唯一唯一且有效的值。
示例表:
<table id="myTable">
<thead>
<tr>
<th class="myHeader">Cat 1</th>
<th>Vol 1</th>
<th class="myHeader">Cat 2</th>
<th>Vol 2</th>
<th class="myHeader">Cat 3</th>
<th>Vol 3</th>
//...
</tr>
</thead>
<tbody>
<tr>
<td class="myClass">item1</td><td>8</td><td class="myClass">item2</td><td>7</td><td class="myClass">item1</td><td>2</td>
</tr>
<tr>
<td class="myClass">item3</td><td>5</td><td class="myClass">item2</td><td>7</td><td class="myClass">item2</td><td>4</td>
</tr>
<tr>
<td class="myClass">item3</td><td>1</td><td class="myClass">item1</td><td>5</td><td class="myClass">item3</td><td>3</td>
</tr>
//...
</tbody>
</table>
我的 JS 到目前为止(不包括重复):
var result = new Array();
$('td').each(function() {
if( ($(this).text() != '') && ($(this).text() != ' ') {
result.push(+($(this).text()));
}
});
alert(result);
提前非常感谢蒂姆。
【问题讨论】:
-
对象非常适合这种情况,因为它们只能包含唯一键。
-
谢谢。你能解释一下我必须在这里改变什么吗?我对 JavaScript 很陌生。
-
请参阅this answer 以从数组中删除重复值。
-
谢谢,马特。您链接中的过滤器解决方案看起来很棒。你知道IE8是否也支持这个吗?