您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

jQuery函数从数组中获取所有唯一元素?

jQuery函数从数组中获取所有唯一元素?

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

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或更低版本,请不要使用不受支持filter方法

除此以外,

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;
    }
}
JS 2022/1/1 18:17:01 有437人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶