zoukankan      html  css  js  c++  java
  • 数组去重代码怎么写?

    <!DOCTYPE html>
    <html>
        <head>
            <title>Array delete duplicate</title>
        </head>
        <body>
            
        </body>
    </html>
    
    <script>
    
    /**
     * 实现一
     * 最容易想到的, 通过两个循环对比返回
     * 正因为使用了两个循环, 因此在最差的情况下, 时间复杂度是O(n^2)
     */
    
        var arr = [1,1,2,2,3,3,4,5,];
        
        Array.prototype.unique1 = function () {
            var newArr = [],
            len = this.length,
            i,j,
            isrepeat;
            
            for(i = 0; i< len; i++) {
                isrepeat = false;
                for(j = 0; j < newArr.length; j++) {
                    if(this[i] == newArr[j]) {
                        isrepeat = true;
                        break; //退出当前整个循环
                    }
                }
                
                if(!isrepeat) {
                    newArr.push(this[i]);
                }
            }
            
            return newArr;
        }
        console.log("unique1: " + arr.unique1() );
    
     /**
     * 实现二
     * 使用了Array的indexOf方法, 减少了一次循环
     * 虽然使用indexOf方法, 减少了一次循环, 但是indexOf方法浏览器的实现, 必定也是需要遍历数组的
     * 但是通过浏览器内核的遍历必定是会比自己循环快得多的
     */
       
        
        Array.prototype.unique2 = function() {
            var newArr = [],
            len = this.length,
            i;
            for(var i = 0; i < len; i++) {
                if(newArr.indexOf(this[i]) > -1) {
                    continue;   //退出本次循环
                }
                newArr.push(this[i]);
            }
            
            return newArr;
        }
        
        console.log("unique2: " + arr.unique2() );
        
       /**
     * 实现三
     * 利用hash表快速查找元素是否存在
     * 考虑到 hash[1] === hash["1"] 的情况, key添加了类型后缀
     */ 
        Array.prototype.unique3 = function () {
            var hash = {},
            len = this.length,
            key = null,
            newArr = [],
            i;
            
            for(i = 0; i < len; i++) {
                key = this[i] + "_" + (typeof this[i]);
                if(hash[key]) {
                    continue;   //退出本次循环,不执行接下来的代码
                }
                hash[key] = true;
                newArr.push(this[i]);
                
            }
            
            console.log(hash)
            return newArr;
        }
        
        console.log("unique3: " + arr.unique3() );
        
        
        
        
        
    </script>
  • 相关阅读:
    7.微软AJAX的解决方案
    6.投票系统
    5.JSON
    4.无刷新评论
    3.输入商品名称后自动弹出其价格示例
    2.JQuery AJAX
    1.AJAX简介
    网站优化
    防抖和节流
    在地址栏输入一次地址会发生什么
  • 原文地址:https://www.cnblogs.com/facial/p/5820200.html
Copyright © 2011-2022 走看看