小结(一)

先做一个小测试(循环性能,仅供参考)

//循环性能测试
// 先定义一个测试数组 
let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20];
// 执行测试
test1();
test2();
test3();
test4();
test5();
test6();
test7();
test8();
test9();
// 循环代码
function test1() {
    console.time('test1');
    for (let i = 0; i < arr.length; i++) {}
    console.timeEnd('test1');
}

function test2() {
    console.time('test2');
    for (let i = 0, len = arr.length; i < len; i++) {}
    console.timeEnd('test2');
}

function test3() {
    console.time('test3');
    let len = arr.length;
    for (let i = 0; i < len; i++) {}
    console.timeEnd('test3');
}

function test4() {
    console.time("test4");
    for (let i in arr) {};
    console.timeEnd('test4');
}

function test5() {
    console.time("test5");
    arr.forEach(function (e) {});
    console.timeEnd("test5");
}

function test6() {
    console.time("test6");
    Array.prototype.forEach.call(arr, function (el) {})
    console.timeEnd("test6");
}

function test7() {
    console.time("test7");
    arr.map(function (e) {})
    console.timeEnd("test7");
}

function test8() {
    console.time("test8");
    for (let i of arr) {}
    console.timeEnd("test8");
}

function test9() {
    console.time("test9");
    for (i of arr) {}
    console.timeEnd("test9");
}

 结果: 

 

 

 

 

 

 

 

 

1. 反转一个三位数

(1)

let n="110";
console.log(n.split("").reverse().join(""));

  (2)

let n = "110";
console.log(n.chartAt(2) + n.charAt(1) + n.charAt(0));

2.阶乘

(1)

 function factorial(n,total){
    if(n=== 1) return total;
    return factorial(n-1,n*total);
 }
 factorial(n,total);

3.字母转大小写

let m = "abc";
m.toUpperCase();//转大写
m.toLowerCase();//转小写

4.数组中最大值

   (1)

let arr = [2, 52, 56, 22, 41, 100, 598, 222, 2, 0, 52];
Math.max(...arr);

   (2)

let arr  = [2, 52, 56, 22, 41, 100, 598, 222, 2, 0, 52];

function sortNumber(a, b) {
     return a - b
}
let arr1 = arr.sort(sortNumber);
arr1.pop();

 5.函数节流

const Throttle = (fn, t) => {
    let last;
    let timer;
    let interval = t || 500;
    return function () {
        let args = arguments;
        let now = +new Date();
        if (last && now - last < interval) {
            clearTimeout(timer);
            timer = setTimeout(() => {
                last = now;
                fn.apply(this, args);
            }, interval);
        } else {
            last = now;
            fn.apply(this, args);
        }
    }
};

6.防抖

function debounce(fun, delay) {
    return function (args) {
        let that = this
        let _args = args
        //每次事件被触发,都会清除当前的timeer,然后重写设置超时调用
        clearTimeout(fun.id)
        fun.id = setTimeout(function () {
            fun.call(that, _args)
        }, delay)
    }
}

 

 

   

posted @ 2020-09-29 17:17  暮雪上的晨星  阅读(130)  评论(0编辑  收藏  举报