欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

常用的前端JavaScript方法封装

程序员文章站 2022-06-23 23:51:22
目录22、兼容getelementsbyclassname方法25、封装自己的foreach方法32、遍历dom树41、requestanimframe兼容性方法42、cancelanimframe兼...

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

function type(para) {
    return object.prototype.tostring.call(para)
}

2、数组去重

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 < len; i++) {
        if (!obj[this[i]]) {
            str += this[i];
            obj[this[i]] = true;
        }
    }
    return str;
}

###### //去除连续的字符串 
function uniq(str) {
    return str.replace(/(\w)\1+/g, '$1')
}

4、深拷贝 浅拷贝

//深克隆(深克隆不考虑函数)
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]') {
                    // 对象
                    result[prop] = {};
                } else {
                    // 数组
                    result[prop] = [];
                }
                deepclone(obj[prop], result[prop])
    } else {
        // 原始值或func
        result[prop] = obj[prop]
    }
  }
}
return result;
}

// 深浅克隆是针对引用值
function deepclone(target) {
    if (typeof (target) !== 'object') {
        return target;
    }
    var result;
    if (object.prototype.tostring.call(target) == '[object array]') {
        // 数组
        result = []
    } else {
        // 对象
        result = {};
    }
    for (var prop in target) {
        if (target.hasownproperty(prop)) {
            result[prop] = deepclone(target[prop])
        }
    }
    return result;
}
// 无法复制函数
var o1 = json.parse(json.stringify(obj1));

5、reverse底层原理和扩展

// 改变原数组
array.prototype.myreverse = function () {
    var len = this.length;
    for (var i = 0; i < len; 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、找出字符串中第一次只出现一次的字母

string.prototype.firstappear = function () {
    var obj = {},
        len = this.length;
    for (var i = 0; i < len; 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级父元素

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

9、 返回元素的第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,解决浏览器的兼容问题

function mychildren(e) {
    var children = e.childnodes,
        arr = [],
        len = children.length;
    for (var i = 0; i < len; 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 < len; i++) {
        if (children[i].nodetype === 1) {
            return true;
        }
    }
    return false;
}

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

element.prototype.insertafter = function (target, elen) {
    var nextelen = elen.nextelenmentsibling;
    if (nextelen == null) {
        this.appendchild(target);
    } else {
        this.insertbefore(target, nextelen);
    }
}

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

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 < 10) {
                i = "0" + i;
       }
      return i;
    }
    return "" + year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒"
}

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

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 {
            // 标准模式
            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、检验字符串是否是回文

function ispalina(str) {
    if (object.prototype.tostring.call(str) !== '[object string]') {
        return false;
    }
    var len = str.length;
    for (var i = 0; i < len / 2; i++) {
        if (str[i] != str[len - 1 - i]) {
            return false;
        }
    }
    return true;
}

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

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 < alldomarray.length; i++) {
        var classarray = trimspace(alldomarray[i].classname).split(' ');
        for (var j = 0; j < classarray.length; j++) {
            if (classarray[j] == _classname) {
                lastdomarray.push(alldomarray[i]);
                break;
            }
        }
    }
    return lastdomarray;
}

23、运动函数

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、弹性运动

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 < len; i++) {
        func.call(_this, this[i], i, this)
    }
}

26、封装自己的filter方法

array.prototype.myfilter = function (func, obj) {
    var len = this.length;
    var arr = [];
    var _this = arguments[1] || window;
    for (var i = 0; i < len; i++) {
        func.call(_this, this[i], i, this) && arr.push(this[i]);
    }
    return arr;
}

27、数组map方法

array.prototype.mymap = function (func) {
    var arr = [];
    var len = this.length;
    var _this = arguments[1] || window;
    for (var i = 0; i < len; i++) {
        arr.push(func.call(_this, this[i], i, this));
    }
    return arr;
}

28、数组every方法

array.prototype.myevery = function (func) {
    var flag = true;
    var len = this.length;
    var _this = arguments[1] || window;
    for (var i = 0; i < len; i++) {
        if (func.apply(_this, [this[i], i, this]) == false) {
            flag = false;
            break;
        }
    }
    return flag;
}

29、数组reduce方法

array.prototype.myreduce = function (func, initialvalue) {
    var len = this.length,
        nextvalue,
        i;
    if (!initialvalue) {
        // 没有传第二个参数
        nextvalue = this[0];
        i = 1;
    } else {
        // 传了第二个参数
        nextvalue = initialvalue;
        i = 0;
    }
    for (; i < len; i++) {
        nextvalue = func(nextvalue, this[i], i, this);
    }
    return nextvalue;
}

30、获取url中的参数

function getwindonhref() {
    var shref = window.location.href;
    var args = shref.split('?');
    if (args[0] === shref) {
        return '';
    }
    var hrefarr = args[1].split('#')[0].split('&');
    var obj = {};
    for (var i = 0; i < hrefarr.length; i++) {
        hrefarr[i] = hrefarr[i].split('=');
        obj[hrefarr[i][0]] = hrefarr[i][1];
    }
    return obj;
}

31、数组排序

// 快排 [left] + min + [right]
function quickarr(arr) {
    if (arr.length <= 1) {
        return arr;
    }
    var left = [],
        right = [];
    var pindex = math.floor(arr.length / 2);
    var p = arr.splice(pindex, 1)[0];
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] <= p) {
            left.push(arr[i]);
        } else {
            right.push(arr[i]);
        }
    }
    // 递归
    return quickarr(left).concat([p], quickarr(right));
}

// 冒泡
function bubblesort(arr) {
    for (var i = 0; i < arr.length - 1; i++) {
        for (var j = i + 1; j < arr.length; j++) {
            if (arr[i] > arr[j]) {
                var temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
    return arr;
}

function bubblesort(arr) {
    var len = arr.length;
    for (var i = 0; i < len - 1; i++) {
        for (var j = 0; j < len - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                var temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
    return arr;
}

32、遍历dom树

 给定页面上的dom元素,将访问元素本身及其所有后代(不仅仅是它的直接子元素)
对于每个访问的元素,函数讲元素传递给提供的回调函数

function traverse(element, callback) {
    callback(element);
    var list = element.children;
    for (var i = 0; i < list.length; i++) {
        traverse(list[i], callback);
    }
}

33、原生js封装ajax

function ajax(method, url, callback, data, flag) {
    var xhr;
    flag = flag || true;
    method = method.touppercase();
    if (window.xmlhttprequest) {
        xhr = new xmlhttprequest();
    } else {
        xhr = new activexobject('microsoft.xmlhttp');
    }
    xhr.onreadystatechange = function () {
        if (xhr.readystate == 4 && xhr.status == 200) {
            console.log(2)
            callback(xhr.responsetext);
        }
    }

    if (method == 'get') {
        var date = new date(),
        timer = date.gettime();
        xhr.open('get', url + '?' + data + '&timer' + timer, flag);
        xhr.send()
        } else if (method == 'post') {
        xhr.open('post', url, flag);
        xhr.setrequestheader('content-type', 'application/x-www-form-urlencoded');
        xhr.send(data);
    }
}

34、异步加载script

function loadscript(url, callback) {
    var oscript = 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管理

var cookie = {
    set: function (name, value, time) {
        document.cookie = name + '=' + value + '; max-age=' + time;
        return this;
    },
    remove: function (name) {
        return this.setcookie(name, '', -1);
    },
    get: function (name, callback) {
        var allcookiearr = document.cookie.split('; ');
        for (var i = 0; i < allcookiearr.length; i++) {
            var itemcookiearr = allcookiearr[i].split('=');
            if (itemcookiearr[0] === name) {
                return itemcookiearr[1]
            }
        }
        return undefined;
    }
}

36、实现bind()方法

function.prototype.mybind = function (target) {
    var target = target || window;
    var _args1 = [].slice.call(arguments, 1);
    var self = this;
    var temp = function () {};
    var f = function () {
        var _args2 = [].slice.call(arguments, 0);
        var parasarr = _args1.concat(_args2);
        return self.apply(this instanceof temp ? this : target, parasarr)
    }
    temp.prototype = self.prototype;
    f.prototype = new temp();
    return f;
}

37、实现call()方法

function.prototype.mycall = function () {
    var ctx = arguments[0] || window;
    ctx.fn = this;
    var args = [];
    for (var i = 1; i < arguments.length; i++) {
        args.push(arguments[i])
    }
    var result = ctx.fn(...args);
    delete ctx.fn;
    return result;
}

38、实现apply()方法

function.prototype.myapply = function () {
    var ctx = arguments[0] || window;
    ctx.fn = this;
    if (!arguments[1]) {
        var result = ctx.fn();
        delete ctx.fn;
        return result;
    }
    var result = ctx.fn(...arguments[1]);
    delete ctx.fn;
    return result;
}

39、防抖

function debounce(handle, delay) {
    var timer = null;
    return function () {
        var _self = this,
            _args = arguments;
        cleartimeout(timer);
        timer = settimeout(function () {
            handle.apply(_self, _args)
        }, delay)
    }
}

40、节流

function throttle(handler, wait) {
    var lasttime = 0;
    return function (e) {
        var nowtime = new date().gettime();
        if (nowtime - lasttime > wait) {
            handler.apply(this, arguments);
            lasttime = nowtime;
        }
    }
}

41、requestanimframe兼容性方法

window.requestanimframe = (function () {
    return window.requestanimationframe ||
        window.webkitrequestanimationframe ||
        window.mozrequestanimationframe ||
        function (callback) {
            window.settimeout(callback, 1000 / 60);
        };
})();

42、cancelanimframe兼容性方法

window.cancelanimframe = (function () {
    return window.cancelanimationframe ||
        window.webkitcancelanimationframe ||
        window.mozcancelanimationframe ||
        function (id) {
            window.cleartimeout(id);
        };
})();

43、jsonp底层方法

function jsonp(url, callback) {
    var oscript = 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上的参数

function geturlparam(surl, skey) {
    var result = {};
    surl.replace(/(\w+)=(\w+)(?=[&|#])/g, function (ele, key, val) {
        if (!result[key]) {
            result[key] = val;
        } else {
            var temp = result[key];
            result[key] = [].concat(temp, val);
        }
    })
    if (!skey) {
        return result;
    } else {
        return result[skey] || '';
    }
}

45、格式化时间

function formatdate(t, str) {
    var obj = {
        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()]
    };
    return str.replace(/([a-z]+)/ig, function ($1) {
        return obj[$1]
    });
}

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

function isavailableemail(semail) {
    var reg = /^([\w+\.])+@\w+([.]\w+)+$/
    return reg.test(semail)
}


47、函数柯里化

是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数且返回结果的新函数的技术

function curryit(fn) {
    var length = fn.length,
        args = [];
    var result = function (arg) {
        args.push(arg);
        length--;
        if (length <= 0) {
            return fn.apply(this, args);
        } else {
            return result;
        }
    }
    return result;
}

48、大数相加

function sumbignumber(a, b) {
    var res = '', //结果
        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;
    }
    return res.replace(/^0+/, '');
}

49、单例模式

function getsingle(func) {
    var result;
    return function () {
        if (!result) {
            result = new func(arguments);
        }
        return result;
    }
}

到此这篇关于常用的前端javascript方法封装的文章就介绍到这了,更多相关前端javascript方法封装内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: JavaScript 封装