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.

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.)

推荐答案

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

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相关问答推荐

通过 Ajax POST 将按钮值从 HTML 发送到 Flask 时出现空数据

为什么 jQuery 不使用 requestAnimationFrame?

如何在使用 jQuery 单击特定链接时打开 bootstrap 导航选项卡的特定选项卡?

使用 bootstrap-datepicker 检测对选定日期的更改

jQuery增量读取AJAX流?

Backbone.js 和 jQuery

jquery:更改URL地址而不重定向?

如何在 jquery 中更新(附加到)href?

从附加元素获取 jQuery 对象的更简单方法

addClass - 可以在同一个 div 上添加多个类吗?

jQuery DataTables:延迟搜索直到输入 3 个字符或单击按钮

如何将数组传递给 jQuery .data() 属性

JQuery Ajax Post 导致 500 内部服务器错误

jQuery:如何从 $.ajax.error 方法中获取 HTTP 状态代码?

数据表日期排序dd/mm/yyyy问题

jQuery slideUp().remove() 在删除发生之前似乎没有显示 slideUp 动画

我可以通过 JavaScript 禁用 CSS :hover 效果吗?

如何淡出显示:inline-block

在jQuery中获取列表元素内容的数组

更改 url 而不使用 javascript 重定向