如何使用$ .unique()函数

Web*_*ars 4 jquery

请帮我理解,如何使用$.unique()功能.

来自文档:

在适当的位置对DOM元素数组进行排序,并删除重复项.

我正在尝试这段代码:

<h1 class="foo">Headline</h1>
<h1 class="foo">Headline</h1>
<h1 class="foo">Headline</h1>

alert( $.unique($('.foo')).length );
Run Code Online (Sandbox Code Playgroud)

它返回3,但我认为1.我错过了什么?看到使用此功能的一些实践示例会很棒.谢谢.

PS

我也尝试过几个数字,但得到了一个非常好奇的结果.以下代码在不同的浏览器中返回不同的值!

$.unique([ 1, 2, 2, 3, 3, 1 ])

  • Safari - 1,2,3,1
  • 歌剧 - 2,1,3
  • FF - 3,2,1,3
  • Chrome - 3,2,1
  • IE - 2,1,3

Roc*_*mat 8

$.unique仅适用于DOM元素的数组.不是其他东西的数组.

在你的情况下,你有3 <h3>秒.它们不是相同的DOM元素,因此$.unique不会删除它们.

<h1 class="foo">Headline</h1>
<h1 class="foo">Headline</h1>
<h1 class="foo">Headline</h1>

alert($.unique($('.foo')).length);  // 3
Run Code Online (Sandbox Code Playgroud)

$.unique 适用于可能多次包含相同元素的数组.

<h1 class="foo otherFoo">Headline</h1>
<h1 class="foo">Headline</h1>

var $foo = $('.foo').get();
var $otherFoo = $('.otherFoo').get();

var $e = $foo.concat($otherFoo);
alert($e.length); // 3
alert($.unique($e).length); // 2
Run Code Online (Sandbox Code Playgroud)

另一方面,如果你想制作$.unique其他东西的排序数组,而不仅仅是DOMElements,你可以做这样的事情(取自这里):

(function($){
    var _old = $.unique;
    $.unique = function(arr){
        // do the default behavior only if we got an array of elements
        if (!!arr[0].nodeType){
            return _old.apply(this,arguments);
        }
        else {
            // reduce the array to contain no dupes via grep/inArray
            return $.grep(arr,function(v,k){
                return $.inArray(v,arr) === k;
            });
        }
    };
})(jQuery);
Run Code Online (Sandbox Code Playgroud)