6

手写32javascript巩固一下子JS基础

 3 years ago
source link: https://segmentfault.com/a/1190000039109381
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

一。数组扁平化

概念:是指将一个多维数组变为一个一维数组。    
    var arr=[1,[2,[3,[4,5]]],6];
    ==>[1, 2, 3, 4, 5, 6]
    方法一:arr.flat(Infinity);
    方法二:JSON.parse("["+JSON.stringify(arr).replace(/\[|]/g,"")+"]")
    方法三: const arrCon=[];
             const fn=arr=>{
                for(let i=0;i<arr.length;i++){
                    if(Array.isArray(arr[i])){
                        fn(arr[i]);
                    }
                    else{
                        arrCon.push(arr[i]);
                    };
                };
              fn(arr);

有不懂flat()小伙伴们可以点击flat()

二。数组去重

var arr=[1,1,2,2,4,4,null,null];
==>[1,2,4,null]
  方法一:Arry.from(new Set(arr));
  方法二:双层for循环
   function FFOR(arr){
          for(var i=0;i<arr.length;i++){
            for(var j=i+1;j<arr.length;j++){
                if(arr[i]===arr[j]){
                    arr.splice(j,1)
                    j--
                }
            }
          }
          return arr;
        };
  方法三:filter()+indexOf()
         function ffor(arr){
            return arr.filter(item,index,arr){
                return arr.indexOf(item,0)===index;
               }
         };
  方法四:indexOf
         function FFOR(arr){
               const arrCon=[];
               for(let i=0;i<arr.length;i++){
                    if(arrCon.indexOf(arr[i])===-1){
                        arrCon.push(arr[i])
                    }
               }
               
               return arrCon
         }   

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK