首页 > 代码库 > Js自定义数组map之bigmap

Js自定义数组map之bigmap

 1         /** 2          * like map,but prev,curr,next and index will be given 3          * @param  {Function} cb Callback,the parameters ara prev,curr,next and index 4          * @return {[type]}      [description] 5          */ 6         Array.prototype.bigmap=function(cb){ 7             var copy = this.slice(0); 8             var len = this.length; 9             for (var i = 0; i < len; i++) {10                 var curr = this[i];11                 var prev = i==0?undefined:this[i-1];12                 var next = i==len?undefined:this[i+1];13                 var ret = cb(curr,prev,next,i);14                 if(ret){15                     copy[i]=ret;16                 }17             }18             return copy;19         }20 21         //写个栗子22         // [1,2,3,4,7,9,10,50]  =>  ["1-4", "7", "9-10", "50"]23 24         var arr = [1,2,3,4,7,9,10,50];25         arr = arr.bigmap(function(curr,prev,next,i){26             // console.log(curr+"--"+prev+"--"+next+"--"+i)27             if(prev+1==curr){28                 var ret = "_";29                 if(next-1!=curr){30                     ret += curr;31                 }32                 return ret;33             }34         }).filter(function(obj){35             return obj!="_";36         }).toString().replace(/,_/g,"-").split(",");37 38         console.log(arr)

 

Js自定义数组map之bigmap