jQuery函数从数组中获取所有唯一元素? [英] jQuery function to get all unique elements from an array?

查看:212
本文介绍了jQuery函数从数组中获取所有唯一元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery.unique 可让您获得数组的唯一元素,但文档说函数主要供内部使用,仅对DOM元素进行操作。另一个SO响应说 unique()函数对数字起作用,但是这个用例不一定是未来的证据,因为它没有在文档中明确说明。

jQuery.unique lets you get unique elements of an array, but the docs say the function is mostly for internal use and only operates on DOM elements. Another SO response said the unique() function worked on numbers, but that this use case is not necessarily future proof because it's not explicitly stated in the docs.

鉴于此,是否存在一个标准jQuery函数,用于仅访问数组中的唯一值(特别是整数等基元)? (显然,我们可以使用 each()函数构造一个循环,但我们是jQuery的新手,并且想知道是否有专用的jQuery函数。)

Given this, is there a "standard" jQuery function for accessing only the unique values — specifically, primitives like integers — in an array? (Obviously, we can construct a loop with the each() function, but we are new to jQuery and would like to know if there is a dedicated jQuery function for this.)

推荐答案

您可以使用 array.filter 返回第一项每个不同的值 -

You can use array.filter to return the first item of each distinct value-

var a = [ 1, 5, 1, 6, 4, 5, 2, 5, 4, 3, 1, 2, 6, 6, 3, 3, 2, 4 ];

var unique = a.filter(function(itm, i, a) {
    return i == a.indexOf(itm);
});

console.log(unique);

如果支持IE8及以下版本是主要版本,请不要使用不受支持的过滤器方法。

If supporting IE8 and below is primary, don't use the unsupported filter method.

否则,

if (!Array.prototype.filter) {
    Array.prototype.filter = function(fun, scope) {
        var T = this, A = [], i = 0, itm, L = T.length;
        if (typeof fun == 'function') {
            while(i < L) {
                if (i in T) {
                    itm = T[i];
                    if (fun.call(scope, itm, i, T)) A[A.length] = itm;
                }
                ++i;
            }
        }
        return A;
    }
}

这篇关于jQuery函数从数组中获取所有唯一元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆