zoukankan      html  css  js  c++  java
  • 前端面试题(一)之JavaScript数组去重的四种方法

    今天,刚刚参加了公司的笔试,关于数组去重,后来简单总结了几种方法,希共勉,为我打call.......

    es5四种方式:
    
    方式一:
    Array.prototype.unique1 = function() {
        // 1. 定义数组
        var temp = [];
        // 2. 遍历当前数组
        for(var i = 0; i < this.length; i++) {
            // 3.如果当前数组的第i已经保存进了临时数组,
            // 那么跳过,否则把当前项push到临时数组里面
            if (-1 === temp.indexOf(this[i])) {
                temp.push(this[i]);
            }
        }
        return temp;
    };方式二:Array.prototype.unique2 = function() {    //1. hash为hash表,r为临时数组
        var hash = {}, temp=[];
        // 2.遍历当前数组
        for(var i = 0; i < this.length; i++)
        {
            // 3. 如果hash表中没有当前项
            if (!hash[this[i]])
            {
                // 4.存入hash表
    hash[this[i]] = true; // 5.把当前数组的当前项push到临时数组里面 temp.push(this[i]); } } return temp; }; 方式三: Array.prototype.unique3 = function() { var n = [this[0]]; for(var i = 1; i < this.length; i++){ if (this.indexOf(this[i]) === i) { n.push(this[i]); } } return n; }; 方式四: Array.prototype.unique4 = function() { this.sort(); var re=[this[0]]; for(var i = 1; i < this.length; i++) { if( this[i] !== re[re.length-1]) { re.push(this[i]); } } return re; }; es6实现方式: Array.prototype.unique = Array.prototype.unique || function () { return [...new Set(this)]; };
    希望大家多多指教,不吝赐教~~

     

     
  • 相关阅读:
    【bzoj1901】dynamic ranking(带修改主席树)
    一堆乱七八糟绝不正经的排序算法
    bzoj2588 Spoj10628. count on a tree
    poj2104 K-th Number
    【bzoj 3595】: [Scoi2014]方伯伯的Oj
    bzoj1926: [Sdoi2010]粟粟的书架
    P3168 [CQOI2015]任务查询系统
    进程和线程
    History of AI
    es6
  • 原文地址:https://www.cnblogs.com/Alex2018/p/9942318.html
Copyright © 2011-2022 走看看