从数组去重这个函数来体验es6的高效率

前几天碰到一个题目,要求是这样的.

题目描述

为 Array 对象添加一个去除重复项的方法

示例1

输入

[false, true, undefined, null, NaN, 0, 1, {}, {}, 'a', 'a', NaN]

输出

[false, true, undefined, null, NaN, 0, 1, {}, {}, 'a']

es5代码

它的在线编辑器只支持es5, 所以写下了一长串代码

Array.prototype.uniq = function () {
    var i = this.length - 1;
    for ( ; i >= 0; i--) {
        for (var j = i - 1; j >= 0; j--) {
            if (this[i] === this[j]) {
                this.splice(i, 1);
                break;
            }
            var isNumber = typeof this[i] === 'number' && typeof this[j] === 'number';
            // 判断两者是否都是NaN
            if (isNumber && isNaN(this[i]) && isNaN(this[j])) {
                this.splice(i, 1);
                break;
            }
            
        }
    }
    return this;
}

两个for循环, 时间复杂度就是 O(n**2) 。

es6代码

Array.prototype.uniq = function() {
  return [...new Set(this)];
}

啊, 这就完了? 没错, 这就完了。解释下上面的代码, Set是es6里面的新对象, 有点雷系数组,但是它的没有重复的值, 数组扩展运算符 [...array], 这里的array可以是数组也可以是类数组对象, 作用就是把array的每一项提取出来作为新数组的一项。

上面的代码不会改变原数组, 如果要改变原数组, 可以修改如下

Array.prototype.uniq = function() {
  const arr = [...new Set(this)];
  this.splice(0, this.length, ...arr);
  return arr;
}
posted @ 2018-08-29 16:58  bingxl  阅读(444)  评论(0编辑  收藏  举报
博客地地址:https://bingxl.cn