JavaScript实用函数

194 阅读1分钟

1. 自己动手实现一个forEach

Array.prototype.forEach = function(fn) {
    var i = 0,
        len = this.length;
    for(;i < len;i++) {
        if(fn.call(this, i, this[i]) === false) break;
    }
}
const arr = [1, 2, 3, 4];
arr.forEach(function(index, item) {
    if(index === 2) return false;
    arr[i] = item * 2
})

2. jQuery链式调用

    var $ = function(dom) {
        if(this instanceof $) {
            this.dom = document.querySelector(dom);
        } else {
            return new $(dom)
        }
    }
    $.prototype = {
        show() {
            this.dom.style.display = 'block';
            return this; // 关键点
        },
        attr(attr, value) {
            this.dom.setAttribute(attr, value);
            return this;
        }
    }
    $(dom).attr('data-id', 1).show();

3. 校验多层级对象

    var obj = {
        common: {},
        person: {
            user: {
                username: 'jacker',
                age: 18
            }
        }
    }
    function interate(obj, key) {
        key = key.split('.');
        var len = key.length,
            result = obj;
        for(var i = 0;i < len;i++) {
            if(result[key[i]] !== undefined) {
                result = result[key[i]]
            } else {
                return undefined
            }
        }
        return result;
    }
    console.log(interate(obj, 'person.user.age')) // 18

4. 函数防抖

// 用户不再操作delay秒后触发函数
function debounce(fn, delay) {
    var timeout;
    return function() {
        clearTimeout(timeout);
        var context = this;
        timeout = setTimeout(function() {
            fn.apply(context, arguments);
        }, delay)
    }
}

5. 函数节流

// 每隔interval秒只触发一次
function throttle(fn, interval) {
    var start = Date.now(), timeout;
    return function() {
        var curr = Date.now(), context = this;
        clearTimeout(timeout);
        if(curr - start >= interval) {
            fn.apply(context, arguments);
        } else {
            timeout = setTimeout(function() {
                fn.apply(context, arguments);
            }, interval)
        }
    }
}