且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 JavaScript 中创建唯一项目列表?

更新时间:2022-12-07 19:31:58

通常,您使用的方法是一个好主意.但我可以提出一个解决方案,让算法更快.

Commonly, the approach you used is a good idea. But I could propose a solution that will make the algorithm a lot faster.

function unique(arr) {
    var u = {}, a = [];
    for(var i = 0, l = arr.length; i < l; ++i){
        if(!u.hasOwnProperty(arr[i])) {
            a.push(arr[i]);
            u[arr[i]] = 1;
        }
    }
    return a;
}

如您所见,我们这里只有一个循环.

As you can see we have only one loop here.

我制作了一个 示例,用于测试您和我的解决方案.试试看吧.

I've made an example that is testing both your and my solutions. Try to play with it.