珠峰培训

JavaScript如何实现合并数组中相同的项

作者:

2014-02-27 17:21:53

194

这也是经常面试会遇到题,现在整理上来供大家参考。

Array.prototype.distinct = function() {
    var a = [1, 2, 3, 4, 2, 1, 4, 5];
    for (var nIndex = 0; nIndex < a.length - 1; nIndex++) {
        for (var i = nIndex + 1; i < a.length;) {
            if (a[nIndex] == a[i]) {
                a.splice(i, 1);
            } else {
                i++;
            }
        }
    }
    return a;
}