常用js函数封装

1、输入一个值,返回其数据类型**

functiontype(para){returnObject.prototype.toString.call(para)}

2、数组去重

functionunique1(arr){return[...newSet(arr)]}functionunique2(arr){varobj={};returnarr.filter(ele=>{if(!obj[ele]){obj[ele]=true;returntrue;}})}functionunique3(arr){varresult=[];arr.forEach(ele=>{if(result.indexOf(ele)==-1){result.push(ele)}})returnresult;}

3、字符串去重

String.prototype.unique=function(){varobj={},str='',len=this.length;for(vari=0;i

4、深拷贝 浅拷贝

//深克隆(深克隆不考虑函数)functiondeepClone(obj,result){varresult=result||{};for(varpropinobj){if(obj.hasOwnProperty(prop)){if(typeofobj[prop]=='object'&&obj[prop]!==null){// 引用值(obj/array)且不为nullif(Object.prototype.toString.call(obj[prop])=='[object Object]'){// 对象result[prop]={};}else{// 数组result[prop]=[];}deepClone(obj[prop],result[prop])}else{// 原始值或funcresult[prop]=obj[prop]}}}returnresult;}// 深浅克隆是针对引用值functiondeepClone(target){if(typeof(target)!=='object'){returntarget;}varresult;if(Object.prototype.toString.call(target)=='[object Array]'){// 数组result=[]}else{// 对象result={};}for(varpropintarget){if(target.hasOwnProperty(prop)){result[prop]=deepClone(target[prop])}}returnresult;}// 无法复制函数varo1=jsON.parse(jsON.stringify(obj1));

5、reverse底层原理和扩展

// 改变原数组Array.prototype.myReverse=function(){varlen=this.length;for(vari=0;i

6、圣杯模式的继承

functioninherit(Target,Origin){functionF(){};F.prototype=Origin.prototype;Target.prototype=newF();Target.prototype.constructor=Target;// 最终的原型指向Target.prop.uber=Origin.prototype;}

7、找出字符串中第一次只出现一次的字母

String.prototype.firstAppear=function(){varobj={},len=this.length;for(vari=0;i

8、找元素的第n级父元素

functionparents(ele,n){while(ele&&n){ele=ele.parentElement?ele.parentElement:ele.parentNode;n--;}returnele;}

9、 返回元素的第n个兄弟节点

functionretSibling(e,n){while(e&&n){if(n>0){if(e.nextElementSibling){e=e.nextElementSibling;}else{for(e=e.nextSibling;e&&e.nodeType!==1;e=e.nextSibling);}n--;}else{if(e.previousElementSibling){e=e.previousElementSibling;}else{for(e=e.previousElementSibling;e&&e.nodeType!==1;e=e.previousElementSibling);}n++;}}returne;}

10、封装mychildren,解决浏览器的兼容问题

functionmyChildren(e){varchildren=e.childNodes,arr=[],len=children.length;for(vari=0;i

11、判断元素有没有子元素

functionhasChildren(e){varchildren=e.childNodes,len=children.length;for(vari=0;i

12、我一个元素插入到另一个元素的后面

Element.prototype.insertAfter=function(target,elen){varnextElen=elen.nextElenmentSibling;if(nextElen==null){this.appendChild(target);}else{this.insertBefore(target,nextElen);}}

13、返回当前的时间(年月日时分秒)

functiongetDateTime(){vardate=newDate(),year=date.getFullYear(),month=date.getMonth()+1,day=date.getDate(),hour=date.getHours()+1,minute=date.getMinutes(),second=date.getSeconds();month=checkTime(month);day=checkTime(day);hour=checkTime(hour);minute=checkTime(minute);second=checkTime(second);functioncheckTime(i){if(i<10){i="0"+i;}returni;}return""+year+"年"+month+"月"+day+"日"+hour+"时"+minute+"分"+second+"秒"}

14、获得滚动条的滚动距离

functiongetScrollOffset(){if(window.pageXOffset){return{x:window.pageXOffset,y:window.pageYOffset}}else{return{x:document.body.scrollLeft+document.documentElement.scrollLeft,y:document.body.scrollTop+document.documentElement.scrollTop}}}

15、获得视口的尺寸

functiongetViewportOffset(){if(window.innerWidth){return{w:window.innerWidth,h:window.innerHeight}}else{// ie8及其以下if(document.compatMode==="BackCompat"){// 怪异模式return{w:document.body.clientWidth,h:document.body.clientHeight}}else{// 标准模式return{w:document.documentElement.clientWidth,h:document.documentElement.clientHeight}}}}

16、获取任一元素的任意属性

functiongetStyle(elem,prop){returnwindow.getComputedStyle?window.getComputedStyle(elem,null)[prop]:elem.currentStyle[prop]}

17、绑定事件的兼容代码

functionaddEvent(elem,type,handle){if(elem.addEventListener){//非ie和非ie9elem.addEventListener(type,handle,false);}elseif(elem.attachEvent){//ie6到ie8elem.attachEvent('on'+type,function(){handle.call(elem);})}else{elem['on'+type]=handle;}}

18、解绑事件

functionremoveEvent(elem,type,handle){if(elem.removeEventListener){//非ie和非ie9elem.removeEventListener(type,handle,false);}elseif(elem.detachEvent){//ie6到ie8elem.detachEvent('on'+type,handle);}else{elem['on'+type]=null;}}

19、取消冒泡的兼容代码

functionstopBubble(e){if(e&&e.stopPropagation){e.stopPropagation();}else{window.event.cancelBubble=true;}}

20、检验字符串是否是回文

functionisPalina(str){if(Object.prototype.toString.call(str)!=='[object String]'){returnfalse;}varlen=str.length;for(vari=0;i

21、检验字符串是否是回文

functionisPalindrome(str){str=str.replace(/\W/g,'').toLowerCase();console.log(str)return(str==str.split('').reverse().join(''))}

22、兼容getElementsByClassName方法

Element.prototype.getElementsByClassName=Document.prototype.getElementsByClassName=function(_className){varallDomArray=document.getElementsByTagName('*');varlastDomArray=[];functiontrimSpace(strClass){varreg=/\s+/g;returnstrClass.replace(reg,' ').trim()}for(vari=0;i

23、运动函数

functionanimate(obj,json,callback){clearInterval(obj.timer);varspeed,current;obj.timer=setInterval(function(){varlock=true;for(varpropinjson){if(prop=='opacity'){current=parseFloat(window.getComputedStyle(obj,null)[prop])*100;}else{current=parseInt(window.getComputedStyle(obj,null)[prop]);}speed=(json[prop]-current)/7;speed=speed>0?Math.ceil(speed):Math.floor(speed);if(prop=='opacity'){obj.style[prop]=(current+speed)/100;}else{obj.style[prop]=current+speed+'px';}if(current!=json[prop]){lock=false;}}if(lock){clearInterval(obj.timer);typeofcallback=='function'?callback():'';}},30)}

24、弹性运动

functionElasticMovement(obj,target){clearInterval(obj.timer);variSpeed=40,a,u=0.8;obj.timer=setInterval(function(){a=(target-obj.offsetLeft)/8;iSpeed=iSpeed+a;iSpeed=iSpeed*u;if(Math.abs(iSpeed)<=1&&Math.abs(a)<=1){console.log('over')clearInterval(obj.timer);obj.style.left=target+'px';}else{obj.style.left=obj.offsetLeft+iSpeed+'px';}},30);}

25、封装自己的forEach方法

Array.prototype.myForEach=function(func,obj){varlen=this.length;var_this=arguments[1]?arguments[1]:window;// var _this=arguments[1]||window;for(vari=0;i

26、封装自己的filter方法

Array.prototype.myFilter=function(func,obj){varlen=this.length;vararr=[];var_this=arguments[1]||window;for(vari=0;i

27、数组map方法

Array.prototype.myMap=function(func){vararr=[];varlen=this.length;var_this=arguments[1]||window;for(vari=0;i

28、数组every方法

Array.prototype.myEvery=function(func){varflag=true;varlen=this.length;var_this=arguments[1]||window;for(vari=0;i

29、数组reduce方法

Array.prototype.myReduce=function(func,initialValue){varlen=this.length,nextValue,i;if(!initialValue){// 没有传第二个参数nextValue=this[0];i=1;}else{// 传了第二个参数nextValue=initialValue;i=0;}for(;i

30、获取url中的参数

functiongetWindonHref(){varsHref=window.location.href;varargs=sHref.split('?');if(args[0]===sHref){return'';}varhrefarr=args[1].split('#')[0].split('&');varobj={};for(vari=0;i

31、数组排序

// 快排 [left] + min + [right]functionquickArr(arr){if(arr.length<=1){returnarr;}varleft=[],right=[];varpIndex=Math.floor(arr.length/2);varp=arr.splice(pIndex,1)[0];for(vari=0;iarr[j]){vartemp=arr[i];arr[i]=arr[j];arr[j]=temp;}}}returnarr;}functionbubbleSort(arr){varlen=arr.length;for(vari=0;iarr[j+1]){vartemp=arr[j];arr[j]=arr[j+1];arr[j+1]=temp;}}}returnarr;}

32、遍历Dom树

// 给定页面上的DOM元素,将访问元素本身及其所有后代(不仅仅是它的直接子元素)// 对于每个访问的元素,函数讲元素传递给提供的回调函数functiontraverse(element,callback){callback(element);varlist=element.children;for(vari=0;i

33、原生js封装ajax

functionajax(method,url,callback,data,flag){varxhr;flag=flag||true;method=method.toUpperCase();if(window.XMLHttpRequest){xhr=newXMLHttpRequest();}else{xhr=newActiveXObject('Microsoft.XMLHttp');}xhr.onreadystatechange=function(){if(xhr.readyState==4&&xhr.status==200){console.log(2)callback(xhr.responseText);}}if(method=='GET'){vardate=newDate(),timer=date.getTime();xhr.open('GET',url+'?'+data+'&timer'+timer,flag);xhr.send()}elseif(method=='POST'){xhr.open('POST',url,flag);xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');xhr.send(data);}}

34、异步加载script

functionloadScript(url,callback){varoscript=document.createElement('script');if(oscript.readyState){// ie8及以下版本oscript.onreadystatechange=function(){if(oscript.readyState==='complete'||oscript.readyState==='loaded'){callback();}}}else{oscript.onload=function(){callback()};}oscript.src=url;document.body.appendChild(oscript);}

35、cookie管理

varcookie={set:function(name,value,time){document.cookie=name+'='+value+'; max-age='+time;returnthis;},remove:function(name){returnthis.setCookie(name,'',-1);},get:function(name,callback){varallCookieArr=document.cookie.split('; ');for(vari=0;i

36、实现bind()方法

Function.prototype.myBind=function(target){vartarget=target||window;var_args1=[].slice.call(arguments,1);varself=this;vartemp=function(){};varF=function(){var_args2=[].slice.call(arguments,0);varparasArr=_args1.concat(_args2);returnself.apply(thisinstanceoftemp?this:target,parasArr)}temp.prototype=self.prototype;F.prototype=newtemp();returnF;}

37、实现call()方法

Function.prototype.myCall=function(){varctx=arguments[0]||window;ctx.fn=this;varargs=[];for(vari=1;i

38、实现apply()方法

Function.prototype.myApply=function(){varctx=arguments[0]||window;ctx.fn=this;if(!arguments[1]){varresult=ctx.fn();deletectx.fn;returnresult;}varresult=ctx.fn(...arguments[1]);deletectx.fn;returnresult;}

39、防抖

functiondebounce(handle,delay){vartimer=null;returnfunction(){var_self=this,_args=arguments;clearTimeout(timer);timer=setTimeout(function(){handle.apply(_self,_args)},delay)}}

40、节流

functionthrottle(handler,wait){varlastTime=0;returnfunction(e){varnowTime=newDate().getTime();if(nowTime-lastTime>wait){handler.apply(this,arguments);lastTime=nowTime;}}}

41、requestAnimFrame兼容性方法

window.requestAnimFrame=(function(){returnwindow.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(callback){window.setTimeout(callback,1000/60);};})();

42、cancelAnimFrame兼容性方法

window.cancelAnimFrame=(function(){returnwindow.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||function(id){window.clearTimeout(id);};})();

43、jsonp底层方法

functionjsonp(url,callback){varoscript=document.createElement('script');if(oscript.readyState){// ie8及以下版本oscript.onreadystatechange=function(){if(oscript.readyState==='complete'||oscript.readyState==='loaded'){callback();}}}else{oscript.onload=function(){callback()};}oscript.src=url;document.body.appendChild(oscript);}

44、获取url上的参数

functiongetUrlParam(sUrl,sKey){varresult={};sUrl.replace(/(\w+)=(\w+)(?=[&|#])/g,function(ele,key,val){if(!result[key]){result[key]=val;}else{vartemp=result[key];result[key]=[].concat(temp,val);}})if(!sKey){returnresult;}else{returnresult[sKey]||'';}}

45、格式化时间

functionformatDate(t,str){varobj={yyyy:t.getFullYear(),yy:(""+t.getFullYear()).slice(-2),M:t.getMonth()+1,MM:("0"+(t.getMonth()+1)).slice(-2),d:t.getDate(),dd:("0"+t.getDate()).slice(-2),H:t.getHours(),HH:("0"+t.getHours()).slice(-2),h:t.getHours()%12,hh:("0"+t.getHours()%12).slice(-2),m:t.getMinutes(),mm:("0"+t.getMinutes()).slice(-2),s:t.getSeconds(),ss:("0"+t.getSeconds()).slice(-2),w:['日','一','二','三','四','五','六'][t.getDay()]};returnstr.replace(/([a-z]+)/ig,function($1){returnobj[$1]});}

46、验证邮箱的正则表达式

functionisAvailableEmail(sEmail){varreg=/^([\w+\.])+@\w+([.]\w+)+$/returnreg.test(sEmail)}

47、函数柯里化

//是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数且返回结果的新函数的技术functioncurryIt(fn){varlength=fn.length,args=[];varresult=function(arg){args.push(arg);length--;if(length<=0){returnfn.apply(this,args);}else{returnresult;}}returnresult;}

48、大数相加

functionsumBigNumber(a,b){varres='',//结果temp=0;//按位加的结果及进位a=a.split('');b=b.split('');while(a.length||b.length||temp){//~~按位非 1.类型转换,转换成数字 2.~~undefined==0 temp+=~~a.pop()+~~b.pop();res=(temp%10)+res;temp=temp>9;}returnres.replace(/^0+/,'');}

49、单例模式

functiongetSingle(func){varresult;returnfunction(){if(!result){result=newfunc(arguments);}returnresult;}}

作者:泪滴在琴上

链接:https://www.jianshu.com/p/cc01443d1359

来源:

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

你可能感兴趣的:(常用js函数封装)