字符串数组上的 jQuery.unique

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10191941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:56:16  来源:igfitidea点击:

jQuery.unique on an array of strings

jquery

提问by Johan

The description of jQuery.unique()states:

jQuery.unique()状态描述:

Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not stringsor numbers.

对 DOM 元素数组进行排序,并删除重复项。请注意,这仅适用于 DOM 元素数组,而不适用于字符串或数字。

With the description in mind, can someone explain why the code below works?

考虑到描述,有人可以解释为什么下面的代码有效吗?

<div></div>
<div></div>?


var arr = ['foo', 'bar', 'bar'];

$.each(arr, function(i, value){
    $('div').eq(0).append(value + ' ');
});

$.each($.unique(arr), function(i, value){
    $('div').eq(1).append(value  + ' ');
});
?

http://jsfiddle.net/essX2/

http://jsfiddle.net/essX2/

Thanks

谢谢

Edit: Possible solution:

编辑:可能的解决方案:

function unique(arr) {
var i,
    len = arr.length,
    out = [],
    obj = { };

for (i = 0; i < len; i++) {
    obj[arr[i]] = 0;
}
for (i in obj) {
    out.push(i);
}
return out;
};

采纳答案by gnarf

It mightwork on an array strings, etc, but it has not been designed for that use...

可能适用于数组字符串等,但它不是为该用途而设计的......

Notice that the code for unique()is hiding in Sizzle as uniqueSort: github source

请注意,代码unique()隐藏在 Sizzle 中为uniqueSortgithub 源

While some of that extra code might seem like it would work on any array, pay close attention to sortOrderas defined here. It does a lot of extra work to put things in "document order" - hence why the documentation states that it should only be used on arrays of DOM elements.

虽然其中一些额外的代码看起来适用于任何数组,但请密切注意sortOrder此处定义的内容。将事物按“文档顺序”排列需要做很多额外的工作——因此文档指出它应该只用于 DOM 元素数组。

回答by gion_13

Although it works, you should probably take into consideration the function description. If the creators say that it is not designed for filtering arrays of anything else than dom elements, you should probably listen to them.
Besides, this functionality is quite easy to be reproduced :

虽然它有效,但您可能应该考虑功能描述。如果创建者说它不是为过滤 dom 元素以外的任何其他数组而设计的,那么您可能应该听听他们的意见。
此外,此功能很容易重现:

function unique(array){
    return array.filter(function(el, index, arr) {
        return index === arr.indexOf(el);
    });
}

(demo page)

演示页面

Update:

更新:

In order for this code to work in all browsers (including ie7 that doesn't support some array features - such as indexOfor filter), here's a rewrite using jquery functionalities :

为了使此代码在所有浏览器(包括不支持某些数组功能的 ie7 - 例如indexOffilter)中工作,这里是使用 jquery 功能重写:

Now here's how the translatedcode should look like:

现在这里是翻译后的代码应该是什么样子:

function unique(array) {
    return $.grep(array, function(el, index) {
        return index === $.inArray(el, array);
    });
}

(demo page)

演示页面

回答by evclid

I know unique works with DOM but this WORKS on arrays of int:

我知道 DOM 的独特作品,但这适用于 int 数组:

$.unique(arr.sort());

回答by xjlin0

If not limited using jQuery, consider to use Set from ES6.

如果不限制使用 jQuery,请考虑使用 ES6 中的 Set。

var arr = ['foo', 'bar', 'bar'];
Array.from(new Set(arr)); // #=> ["foo", "bar"]

Working for Firefox 45, Safari 9 and Chrome 49.

适用于 Firefox 45、Safari 9 和 Chrome 49。

回答by davegaeddert

There's a quick way to extend the jQuery.unique() function to work on arrays containing elements of any type.

有一种快速的方法可以扩展 jQuery.unique() 函数以处理包含任何类型元素的数组。

(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);

// in use..
var arr = ['first',7,true,2,7,true,'last','last'];
$.unique(arr); // ["first", 7, true, 2, "last"]

var arr = [1,2,3,4,5,4,3,2,1];
$.unique(arr); // [1, 2, 3, 4, 5]

http://www.paulirish.com/2010/duck-punching-with-jquery/- example #2

http://www.paulirish.com/2010/duck-punching-with-jquery/- 示例 #2

回答by Blazemonger

$.uniquewill remove duplicateDOM elements, not identicalDOM elements. When you try to use it on strings, you get unpredictable behavior and the sorting will (probably) fail.

$.unique将删除重复的DOM 元素,而不是相同的DOM 元素。当您尝试在字符串上使用它时,您会得到不可预测的行为,并且排序将(可能)失败。

It's a function intended for internal use by jQuery only, and won't be useful to mere mortals like you and I.

这是一个仅供 jQuery 内部使用的函数,对像你和我这样的凡人没有用。

回答by brotherol

$.unique will only remove duplicate DOM element, if you need it for array :

$.unique 只会删除重复的 DOM 元素,如果数组需要它:

var result=[] ;
$.each([12,1,2,4,3,1,4,3,3,2,111], 
        function(i,e){ if($.inArray(e,result)===-1) result.push(e) ;});
result;

回答by Mainak Ray

var array=['a','b','c','a'];

    function unique(array)
    {
    var unique_arr=[];
    array.forEach(function(i,e)
    {
    if(unique_arr.indexOf(i)===-1) unique_arr.push(i);
    });
    return unique_arr;
    }
    console.log(unique(array));