zoukankan      html  css  js  c++  java
  • js 数组去重复的方法

    数组去重复是js中常用的方法,归纳了四种如下:

    1. for + indexOf  去重复

    1       var arr = [3,5,5,4,1,1,2,3,7,2,5];
    2       var target = [];
    3       for(var i=0,len=arr.length;i<len;i++){
    4         if( target.indexOf(arr[i])==-1 ){
    5           target.push(arr[i]);
    6         }
    7       };
    8       console.log(target);

    2. forEach + indexOf 去重复

    1       var arr = [3,5,5,4,1,1,2,3,7,2,5];
    2       var target = [];
    3       arr.forEach(function(val){
    4         if(this.indexOf(val)==-1){
    5           this.push(val);
    6         };
    7       },target);
    8       console.log(target);

    3.原型对象 prototype + for + indexOf 去重复

     1       Array.prototype.quchong = function(){
     2         var target = [] ;
     3         for(var i=0,len=this.length;i<len;i++){
     4           if(target.indexOf(this[i])==-1){
     5             target.push(this[i]);
     6           }
     7         };
     8         return target;
     9       };
    10       var arr = [3,5,5,4,1,1,2,3,7,2,5];
    11       console.log(arr.quchong());

    4.原型对象 prototype + forEach + indexOf 去重复

     1       Array.prototype.quchong = function(){
     2         var target = [];
     3         this.forEach(function(val){
     4           if(this.indexOf(val)==-1){
     5             this.push(val);
     6           }
     7         },target);
     8         return target;
     9       };
    10       var arr = [3,5,5,4,1,1,2,3,7,2,5];
    11       console.log(arr.quchong());

    运行结果:

    http://www.cnblogs.com/huanying2015 博客随笔大多数文章均属原创,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利
  • 相关阅读:
    zepto的源代码注释(转)
    关于js的连续赋值
    一道js题
    深入理解setTimeout的作用域
    深入理解setTimeout和setinterval
    webapp之路--apple私有属性apple-touch-icon
    javascript中的原型继承
    webapp之路--百度手机前端经验(转)
    (转)浏览器的渲染原理
    node.js study: cluster
  • 原文地址:https://www.cnblogs.com/huanying2015/p/8029034.html
Copyright © 2011-2022 走看看