js方法积累

2019-06-11  本文已影响0人  chasing_dream
//数幂的实现
function fun(a, b) {
    if(typeof a != "number" || typeof b != "number" ) return console.log("你输入的类型不对");
    var num = a;
    for (var i = b - 1; i > 0; i--) {
        num *= a;
    }
    console.log(num);
    }
fun(2,3);
阶乘的实现
function fun(a) {
    if(typeof a != "number" || a < 0 ) return console.log("你输入的类型不对");
    var num = 1;
    for (var i = 1; i <= a; i++) {
        num *= i;
    }
    console.log(num);
    }
fun(0);

//递归的实现;必须有出口;有一定的规律;

function factorial(n) {
    if(n==0 || n==1) {
        return 1;
    } else {
        return n * factorial(n-1);
    }
}
//函数角度性能优化函数记忆
function memorize(fn) {
    var cache = {};
    return function() {
        var key = arguments.length + Array.prototype.join.call(arguments);
        if(cache[key]) {
            return cache[key]
        } else {
            cache[key] = fn.apply(this, arguments);
            return cache[key]
        }
    }
}
console.log(factorial(5))
var newF = memorize(factorial)
console.time('first');
console.log(newF(5));
console.timeEnd('two');
console.time('first');
console.log(newF(5));
console.timeEnd('two');
//事件节流
<div id="show">0</div>
<button id="btn">click</button>
<script>
var oDiv =document.getElementById('show');
var oBtn =document.getElementById('btn');

function throttle(handler, wait) {
    var lastTime = 0;
    return function(e) {
        var nowTime = new Date().getTime();
        if(nowTime - lastTime > wait) {
            // handler();
            handler.apply(this, arguments)
            lastTime = nowTime;
        }
    }
}
function buy(e) {
    console.log(this,e)
    oDiv.innerText = parseInt(oDiv.innerText) + 1;
}
oBtn.onclick = throttle(buy, 1000)

</script>
//页面请求——防抖
<input type="text" id="inp">
<script>
var oInp = document.getElementById('inp');
function debounce(handler, delay) {
    var timer = null;
    return function(e) {
        var _self = this, _arg = arguments;
        clearTimeout(timer);
        timer = setTimeout(function() {
            handler.apply(_self, _arg);
        }, delay)
    }

}
function ajax(e) {
    console.log(e, this.value);
}
oInp.oninput = debounce(ajax, 2000)


上一篇 下一篇

猜你喜欢

热点阅读