zoukankan      html  css  js  c++  java
  • 数组去重和数组拍平

    1 简单数组去重

     1 Array.prototype.unique = function(){
     2          var obj={},res=[]; //temp用于存放去重后的元素
     3 
     4          for(var i=0;i<this.length;i++){
     5              var temp = this[i];
     6              if(!obj[ (typeof temp) + temp ]){
     7                  res.push(temp);
     8                  obj[ (typeof temp) + temp ] =true;
     9              }
    10          }
    11 
    12          return res;
    13     };
    14     var arr = [1,2,1,'1','2',3];
    15     console.log(arr.unique());

    2 多种数据类型的数组去重

     1 Array.prototype.multiUnipque = function (){
     2         //判断对象类型的方法
     3         var isEqual = function (obj1, obj2){
     4             //判断两个对象的地址是否一样,地址一样则必相等,这里只为了优化性能
     5             if(obj1 === obj2){
     6                 return true;
     7             }
     8             if(typeof(obj1)=="object"&&typeof(obj2)=="object"){
     9                 //判断两个对象类型一致且为object类型
    10                 var count= 0;
    11                 for(var attr in obj1){
    12                     count++;
    13                     if(!isEqual(obj1[attr],obj2[attr])){
    14                         return false;
    15                     }
    16                 }
    17                 for(var attr in obj2){
    18                     count--;
    19                 }
    20                 return count==0;
    21             }else if(typeof(obj1)=="function"&&typeof(obj2)=="function"){
    22                 //判断两个对象类型一致且为function类型
    23                 if(obj1.toString()!==obj2.toString()){
    24                     return false;
    25                 }
    26             }else {    //判断两个对象类型不一致,再判断值是否相等
    27                 if(obj1!=obj2){
    28                     return false;
    29                 }
    30             }
    31             return true;
    32         }
    33 
    34         //temp作为传入数组arr的备份,在不改变原数组的基础上进行去重操作
    35         var temp=this.slice(0);
    36         for(var i=0;i<temp.length;i++){
    37             for(var j=i+1;j<temp.length;j++){
    38                 if(isEqual(temp[j],temp[i])){
    39                     temp.splice(j,1);//删除该元素
    40                     j--;
    41                 }
    42             }
    43         }
    44         return temp;
    45     }
    46 
    47     var arr = [1,2,1,'1','2',3,[1],[1],{a:1,b:2},{a:1},{a:1,b:2}];
    48     console.log(arr.multiUnipque());

    3 应用:数组拍平

    用数组方法实现如下:

     var arr = [1, [2, [3, 4]]];

    arr.toString().split(",").map(function(item){ return +item; }) ;

    用模拟方法实现:

  • 相关阅读:
    Object类学习
    Thread.State 线程状态
    Thread.UncaughtExceptionHandler
    apply和call的区别
    如何实现border-width:0.5px;
    table固定头部,表格tbody可上下左右滑动
    canvas画布实现手写签名效果
    ES6学习笔记
    for循环中执行setTimeout问题
    javaScript函数提升及作用域
  • 原文地址:https://www.cnblogs.com/guoyongfeng/p/3903047.html
Copyright © 2011-2022 走看看