Skip to content

Latest commit

History

50 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

一些常用的函数

js实现LazyMan

Lazyman.js

js封装ajax,jsonp

Ajax.js

js双向绑定

doublebinding.js

js十种排序算法

Sort.md

返回带逗号的数字

functionnumberWithCommas(x){returnx.toString().replace(/\B(?=(\d{3})+(?!\d))/g,',')}

是否是数组

functionisArray(arr){returntypeofArray.isArray==='function' ?
Array.isArray(arr) : Object.prototype.toString.call(arr)==='[Object Array]'}

数组去重

Array.prototype.unique=function(){return[...newSet(this)]}
functionunique(arr){lettempArr=[]arr.map((v)=>{if(!(vintempArr)){tempArr[tempArr.length]=v}})returntempArr}
Array.prototype.unique=function(){letres=this.sort(),returnres.filter((v,i,context)=>{returnv!==context[i+1]})}

获取随机颜色值

functiongetRandomColor(){letcolor='#',letters='0123456789abcdef'for(leti=0;i<6;i++){color+=letters[Math.round(Math.random()*letters.length)]}returncolor}
functionrandomColor(){letcolor='rgba('for(i=0;i<3;i++){color+=`${Math.round(Math.random()*255)},`}returncolor+=`${Math.random().toFixed(1)})`}

hexToRgb

functionhexToRgb(hex){constresult=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)return!!result ? {r: parseInt(result[1],16),g: parseInt(result[2],16),b: parseInt(result[3],16),} : null}

数组乱序

functionshuffle(arr){for(leti=arr.length;i;i--){letj=Math.floor(Math.random()*i);[arr[i-1],arr[j]]=[arr[j],arr[i-1]];//ES6解构赋值}}
[1,2,3,4,5].sort(()=>{returnMath.random()>.5 ? 1 : -1})
functionshuffle(arr){letrandom=0,result=[],origin=[]arr.map(item=>{origin.push(item)})while(arr.length>0){random=Math.floor(Math.random()*arr.length)//生产原数组随机索引result.push(arr[random])//向结果数组添加元素arr.splice(random,1)//删除原数组元素}return{
result,
origin
}}

数字求和

functionforSum(n){if(typeofn!=='number'){return}letsum=0for(n;n>=1;n--){sum+=n}returnsum}

函数柯里化

functionsum(item){varcur=item;varinner=function(next){returnnext==null ? cur : (cur+=next,inner)};returnitem==null ? undefined : inner}

冒泡排序

functionbubbleSort(arr){constlen=arr.lengthfor(leti=0;i<len;i++){for(letj=0;j<len-1;j++){if(arr[j]>arr[j+1]){[arr[j],arr[j+1]]=[arr[j+1],arr[j]]}}}returnarr}

对象深拷贝

functiondeepCopy(parent,child){child=child||{}if(typeofparent!=='object'){return}for(letiteminparent){if(parent.hasOwnProperty(item)){if(typeofparent[item]==='object'){child[item]=Array.isArray(parent[item])? [] : {}deepCopy(parent[item],child[item])}else{child[item]=parent[item]}}}returnchild}
constcopy=JSON.parse(JSON.stringify(source))

变量交换

functionchange(a,b){return[a,b]=[b,a]}

寻找数组中最大值与最小值得差值

functiondiff(arr){returnMath.max(...arr)-Math.min(...arr)}

获取n天前/后的日期

functiongetDayBeforeAfter(date,type,days){date=date||newDate()type=type||'after'days=days||1if(!(dateinstanceofDate)){if(date.indexOf('-')!=-1){date.replace(/\-/g,'/')}date=newDate(date)}letnewDate=dateswitch(type){case"after":
newDate=newDate(date.getTime()+(days*24*60*60*1000))breakcase"before":
newDate=newDate(date.getTime()-(days*24*60*60*1000))break}return`${newDate.getFullYear()}/`+`${newDate.getMonth()+1}/`+`${newDate.getDate()}`}

使用Promise对象处理ajax请求

functionpromiseAjax(url){returnnewPromise(function(resolve,reject){constxhr=newXMLHttpRequest()xhr.open('GET',url,true)xhr.onload=function(){if(xhr.status>=200&&xhr.status<400){letdata=JSON.parse(xhr.responseText)resovle(data)}else{reject(newError(xhr.statusText))}}xhr.onerror=function(){reject(newError(xhr.statusText))}xhr.send()})}letURL='http://news-at.zhihu.com/api/4/news/latest'promiseAjax(URL).then(function(data){console.log(data)}).catch(function(err){console.log(err)})

Fetch API

consturl=URL.fomat({pathname:''})constheaders=newHeaders({'Content-type':'application/json'})constrequest=newRequest(url,{method:'get',mode:'cors',credentials:'include',
headers,body:JSON.stringify(body)})constreponse=awaitfetch(request)constdata=awaitreponse.json()

字符串重复

String.prototype.repeatify=String.prototype.repeatify||function(n){if(typeofn!=='number')returnletstr=''for(leti=0;i<n;i++){str+=this}returnstr}

数字左补全

functionleftPad(num){letn=parseInt(num,10)returnn>0 ? (n<=9 ? '0'+n : n) : '00'}

斐波那契数列

functionfibonacci(n){constres=[1,1]if(typeofn!=='number')returnif(n===0)returnreswhile(n>0){res.push(res[res.length-2]+res[res.length-1])n--}returnres}

阶乘

functionfactorial(n){functionfact(n,res){if(n<2)returnresreturnfact(n-1,n*res)}returnfact(n,1)}

生成随机字符串

functiongetRandomString(n){if(typeofn!='number')returnletstr=""for(;str.length<n;str+=Math.random().toString(36).substr(2)){}returnstr.substr(0,n)}

将浮点数左边的数每3位加逗号

functioncommafy(num){returnnum&&num.toString().replace(/(\d)(?=(\d{3})+\.)/g,($1,$2)=>{return$2+=','})}

函数防抖

functiondebounce(fn,delay){lettimer=nullreturnfunction(){constself=thisletargs=argumentsclearTimeout(timer)timer=setTimeout(()=>{fn.apply(self,args)},delay)}}

实现indexOf

Array.prototype.indexOf=Array.prototype.indexOf||function(ele,fromIndex){if(this===null||!ele){return-1}letlength=this.lengthleti=fromIndex||0letcur=-1while(true){if(this[i]===ele){cur=ibreak}else{i++if(length===i){break}continue}}returncur}

About

一些常用的js函数

Topics

Resources

Stars

9 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages