【问题标题】:jQuery: create array with all unique values of a tablejQuery:使用表的所有唯一值创建数组
【发布时间】: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是否也支持这个吗?

标签: jquery arrays push each


【解决方案1】:

试试这个

var result = new Array();
$('td').each(function() {
    if( ($(this).text() != '') && ($(this).text() != ' ') {
        if(result.indexOf($(this).text()) == -1){
            result.push(+($(this).text()));
        }
    }
});
alert(result);

【讨论】:

  • 也谢谢你!
  • 我想我会选择这个,因为它似乎适用于所有浏览器。如果我只想考虑某个类的 TD,我会说 $('td.myClass')... 吗?
  • 谢谢。使用 td.myClass 只会为所有值返回 NaN。
  • 好的,我得到了这个工作。我不得不改变 result.push 行如下: result.push( $(this).text() );
【解决方案2】:

你可以在后面使用$.unique()

result = $.unique(result);

或事先检查:

if(result.indexOf(this.textContent) == -1){
    //push
}

【讨论】:

  • 谢谢。 IE8 和 IE9 支持 $.unique 吗?
  • 是的,如果你使用 jquery 1.x,不能保证 2.x 以后没有测试过。
  • 谢谢。我对此进行了测试,但在我的情况下它不会删除重复项。
  • 奇怪的是你在each() 之后做了吗?
【解决方案3】:

你可以这样做:

var result = new Array();

$('#myTable').find('td.myClass').each(function () {
   if (result.indexOf($(this).text()) == -1) {
       result.push($.trim($(this).text()));
   }
});
console.log(result);

Fiddle


$.inArray():

var result = [];

$('#myTable').find('td.myClass').each(function () {
   if ($.inArray($(this).text(), result) == -1) {
      result.push($.trim($(this).text()));
   }
});
console.log(result);

With jQuery.inArray()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 1970-01-01
    • 2022-06-29
    • 2022-01-22
    • 1970-01-01
    • 2012-01-16
    相关资源
    最近更新 更多