1. 常用的前端 JavaScript 方法封裝(上)

        共 733字,需瀏覽 2分鐘

         ·

        2021-02-20 13:10

        作者:小蘑菇
        來(lái)源:SegmentFault 思否社區(qū)



        1、輸入一個(gè)值,返回其數(shù)據(jù)類型

        function?type(para)?{
        ????return?Object.prototype.toString.call(para)
        }

        2、數(shù)組去重

        function?unique1(arr)?{
        ????return?[...new?Set(arr)]
        }

        function?unique2(arr)?{
        ????var?obj?=?{};
        ????return?arr.filter(ele?=>?{
        ????????if?(!obj[ele])?{
        ????????????obj[ele]?=?true;
        ????????????return?true;
        ????????}
        ????})
        }

        function?unique3(arr)?{
        ????var?result?=?[];
        ????arr.forEach(ele?=>?{
        ????????if?(result.indexOf(ele)?==?-1)?{
        ????????????result.push(ele)
        ????????}
        ????})
        ????return?result;
        }

        3、字符串去重

        String.prototype.unique?=?function?()?{
        ????var?obj?=?{},
        ????????str?=?'',
        ????????len?=?this.length;
        ????for?(var?i?=?0;?i?????????if?(!obj[this[i]])?{
        ????????????str?+=?this[i];
        ????????????obj[this[i]]?=?true;
        ????????}
        ????}
        ????return?str;
        }

        ######?//去除連續(xù)的字符串?
        function?uniq(str)?{
        ????return?str.replace(/(\w)\1+/g,?'$1')
        }

        4、深拷貝 淺拷貝

        //深克?。ㄉ羁寺〔豢紤]函數(shù))
        function?deepClone(obj,?result)?{
        ????var?result?=?result?||?{};
        ????for?(var?prop?in?obj)?{
        ????????if?(obj.hasOwnProperty(prop))?{
        ????????????if?(typeof?obj[prop]?==?'object'?&&?obj[prop]?!==?null)?{
        ????????????????//?引用值(obj/array)且不為null
        ????????????????if?(Object.prototype.toString.call(obj[prop])?==?'[object?Object]')?{
        ????????????????????//?對(duì)象
        ????????????????????result[prop]?=?{};
        ????????????????}?else?{
        ????????????????????//?數(shù)組
        ????????????????????result[prop]?=?[];
        ????????????????}
        ????????????????deepClone(obj[prop],?result[prop])
        ????}?else?{
        ????????//?原始值或func
        ????????result[prop]?=?obj[prop]
        ????}
        ??}
        }
        return?result;
        }

        //?深淺克隆是針對(duì)引用值
        function?deepClone(target)?{
        ????if?(typeof?(target)?!==?'object')?{
        ????????return?target;
        ????}
        ????var?result;
        ????if?(Object.prototype.toString.call(target)?==?'[object?Array]')?{
        ????????//?數(shù)組
        ????????result?=?[]
        ????}?else?{
        ????????//?對(duì)象
        ????????result?=?{};
        ????}
        ????for?(var?prop?in?target)?{
        ????????if?(target.hasOwnProperty(prop))?{
        ????????????result[prop]?=?deepClone(target[prop])
        ????????}
        ????}
        ????return?result;
        }
        //?無(wú)法復(fù)制函數(shù)
        var?o1?=?jsON.parse(jsON.stringify(obj1));

        5、reverse底層原理和擴(kuò)展

        //?改變?cè)瓟?shù)組
        Array.prototype.myReverse?=?function?()?{
        ????var?len?=?this.length;
        ????for?(var?i?=?0;?i?????????var?temp?=?this[i];
        ????????this[i]?=?this[len?-?1?-?i];
        ????????this[len?-?1?-?i]?=?temp;
        ????}
        ????return?this;
        }

        6、圣杯模式的繼承

        function?inherit(Target,?Origin)?{
        ????function?F()?{};
        ????F.prototype?=?Origin.prototype;
        ????Target.prototype?=?new?F();
        ????Target.prototype.constructor?=?Target;
        ????//?最終的原型指向
        ????Target.prop.uber?=?Origin.prototype;
        }

        7、找出字符串中第一次只出現(xiàn)一次的字母

        String.prototype.firstAppear?=?function?()?{
        ????var?obj?=?{},
        ????????len?=?this.length;
        ????for?(var?i?=?0;?i?????????if?(obj[this[i]])?{
        ????????????obj[this[i]]++;
        ????????}?else?{
        ????????????obj[this[i]]?=?1;
        ????????}
        ????}
        ????for?(var?prop?in?obj)?{
        ???????if?(obj[prop]?==?1)?{
        ?????????return?prop;
        ???????}
        ????}
        }

        8、找元素的第n級(jí)父元素

        function?parents(ele,?n)?{
        ????while?(ele?&&?n)?{
        ????????ele?=?ele.parentElement???ele.parentElement?:?ele.parentNode;
        ????????n--;
        ????}
        ????return?ele;
        }

        9、?返回元素的第n個(gè)兄弟節(jié)點(diǎn)

        function?retSibling(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++;
        ????????}
        ????}
        ????return?e;
        }

        10、封裝mychildren,解決瀏覽器的兼容問(wèn)題

        function?myChildren(e)?{
        ????var?children?=?e.childNodes,
        ????????arr?=?[],
        ????????len?=?children.length;
        ????for?(var?i?=?0;?i?????????if?(children[i].nodeType?===?1)?{
        ????????????arr.push(children[i])
        ????????}
        ????}
        ????return?arr;
        }

        11、判斷元素有沒有子元素

        function?hasChildren(e)?{
        ????var?children?=?e.childNodes,
        ????????len?=?children.length;
        ????for?(var?i?=?0;?i?????????if?(children[i].nodeType?===?1)?{
        ????????????return?true;
        ????????}
        ????}
        ????return?false;
        }

        12、我一個(gè)元素插入到另一個(gè)元素的后面

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

        13、返回當(dāng)前的時(shí)間(年月日時(shí)分秒)

        function?getDateTime()?{
        ????var?date?=?new?Date(),
        ????????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);
        ?????function?checkTime(i)?{
        ????????if?(i?????????????????i?=?"0"?+?i;
        ???????}
        ??????return?i;
        ????}
        ????return?""?+?year?+?"年"?+?month?+?"月"?+?day?+?"日"?+?hour?+?"時(shí)"?+?minute?+?"分"?+?second?+?"秒"
        }

        14、獲得滾動(dòng)條的滾動(dòng)距離

        function?getScrollOffset()?{
        ????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、獲得視口的尺寸

        function?getViewportOffset()?{
        ????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?{
        ????????????//?標(biāo)準(zhǔn)模式
        ????????????return?{
        ????????????????w:?document.documentElement.clientWidth,
        ????????????????h:?document.documentElement.clientHeight
        ????????????}
        ????????}
        ????}
        }

        16、獲取任一元素的任意屬性

        function?getStyle(elem,?prop)?{
        ????return?window.getComputedStyle???window.getComputedStyle(elem,?null)[prop]?:?elem.currentStyle[prop]
        }

        17、綁定事件的兼容代碼

        function?addEvent(elem,?type,?handle)?{
        ????if?(elem.addEventListener)?{?//非ie和非ie9
        ????????elem.addEventListener(type,?handle,?false);
        ????}?else?if?(elem.attachEvent)?{?//ie6到ie8
        ????????elem.attachEvent('on'?+?type,?function?()?{
        ????????????handle.call(elem);
        ????????})
        ????}?else?{
        ????????elem['on'?+?type]?=?handle;
        ????}
        }

        18、解綁事件

        function?removeEvent(elem,?type,?handle)?{
        ????if?(elem.removeEventListener)?{?//非ie和非ie9
        ????????elem.removeEventListener(type,?handle,?false);
        ????}?else?if?(elem.detachEvent)?{?//ie6到ie8
        ????????elem.detachEvent('on'?+?type,?handle);
        ????}?else?{
        ????????elem['on'?+?type]?=?null;
        ????}
        }

        19、取消冒泡的兼容代碼

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

        20、檢驗(yàn)字符串是否是回文

        function?isPalina(str)?{
        ????if?(Object.prototype.toString.call(str)?!==?'[object?String]')?{
        ????????return?false;
        ????}
        ????var?len?=?str.length;
        ????for?(var?i?=?0;?i?????????if?(str[i]?!=?str[len?-?1?-?i])?{
        ????????????return?false;
        ????????}
        ????}
        ????return?true;
        }

        21、檢驗(yàn)字符串是否是回文

        function?isPalindrome(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)?{
        ????var?allDomArray?=?document.getElementsByTagName('*');
        ????var?lastDomArray?=?[];
        ????function?trimSpace(strClass)?{
        ????????var?reg?=?/\s+/g;
        ????????return?strClass.replace(reg,?'?').trim()
        ????}
        ????for?(var?i?=?0;?i?????????var?classArray?=?trimSpace(allDomArray[i].className).split('?');
        ????????for?(var?j?=?0;?j?????????????if?(classArray[j]?==?_className)?{
        ????????????????lastDomArray.push(allDomArray[i]);
        ????????????????break;
        ????????????}
        ????????}
        ????}
        ????return?lastDomArray;
        }

        23、運(yùn)動(dòng)函數(shù)

        function?animate(obj,?json,?callback)?{
        ????clearInterval(obj.timer);
        ????var?speed,
        ????????current;
        ????obj.timer?=?setInterval(function?()?{
        ????????var?lock?=?true;
        ????????for?(var?prop?in?json)?{
        ????????????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);
        ????????????typeof?callback?==?'function'???callback()?:?'';
        ????????}
        ????},?30)
        }

        24、彈性運(yùn)動(dòng)


        function?ElasticMovement(obj,?target)?{
        ????clearInterval(obj.timer);
        ????var?iSpeed?=?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)?{
        ????var?len?=?this.length;
        ????var?_this?=?arguments[1]???arguments[1]?:?window;
        ????//?var?_this=arguments[1]||window;
        ????for?(var?i?=?0;?i?????????func.call(_this,?this[i],?i,?this)
        ????}
        }



        點(diǎn)擊左下角閱讀原文,到?SegmentFault 思否社區(qū)?和文章作者展開更多互動(dòng)和交流,掃描下方”二維碼“或在“公眾號(hào)后臺(tái)回復(fù)“?入群?”即可加入我們的技術(shù)交流群,收獲更多的技術(shù)文章~

        -?END -


        瀏覽 21
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
        評(píng)論
        圖片
        表情
        推薦
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
          
          

            1. 一区视频在线播放 | 伊人婷婷五月 | 秋霞在线观看视频 | 久久偷拍网 | 女生操逼免费视频 |