zoukankan      html  css  js  c++  java
  • 从数组去重这个函数来体验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;
    }
    
  • 相关阅读:
    react开发环境搭建
    react 组件创建
    Redux 视频教程
    echars3.0 柱状图y轴字体斜放
    echars3.0 柱状图大小设置
    ECharts地图详解 【转】
    html 超出出现省略号
    html JS打印添加水印图片
    js 重庆38区县 数组
    docker 暴露2375 端口。
  • 原文地址:https://www.cnblogs.com/scarecrowlxb/p/9555435.html
Copyright © 2011-2022 走看看