Fork me on GitHub

前端高频手撕代码整理(二)

前端高频手撕代码整理(一)

1.手写count

使用闭包:

var count = (
    function(){
        let a = 0
        return function () {
            console.log(++a)
        }
    }
)()

count() // 1
count() // 2
count() // 3

2. 手写sleep睡眠函数

es5一般方法

// es5
function sleep(callback, delay) {
    if(typeof callback == 'function'){
        setTimeout(callback, delay)
    }
}

function output() {
    console.log("delay output")
}
// output不能写output(), 否则就要立即执行啦!
sleep(output, 2000)

使用promise

const sleep = (delay)=> {
    return new Promise(resolve => {
        setTimeout(resolve, delay)
    })
}
sleep(2000).then(()=>{
    console.log("delay output")
})

3.手写forEach

arr.forEach(function(currentValue, currentIndex, arr) {}, thisArg)

//currentValue  必需。当前元素
//currentIndex  可选。当前元素的索引
//arr           可选。当前元素所属的数组对象。
//thisArg       可选参数。当执行回调函数时,用作 this 的值。
Array.prototype._forEach = function(fn, thisArg) {
    if (typeof fn !== 'function') throw "参数必须为函数";
    if(!Array.isArray(this)) throw "只能对数组使用forEach方法";
    let arr = this;
    for(let i=0; i<arr.length; i++) {
        fn.call(thisArg, arr[i], i, arr)
    }
}

// test
let arr = [1,2,3,4,5];
arr._forEach((item, index) => {
    console.log(item, index);
})

// test thisArg

function Counter() {
    this.sum = 0;
    this.count = 0;
}
// 因为 thisArg 参数(this)传给了 forEach(),每次调用时,它都被传给 callback 函数,作为它的 this 值。
Counter.prototype.add = function (array) {
    array._forEach(function (entry) {
        this.sum += entry;
        ++this.count;
    }, this);
      // ^---- Note
};

const obj = new Counter();
obj.add([2, 5, 9]);

console.log(obj.count); // 3 === (1 + 1 + 1)
console.log(obj.sum);  // 16 === (2 + 5 + 9)
posted @   zerozhupan  阅读(131)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示
目 录 X
1.手写count
2. 手写sleep睡眠函数
es5一般方法
使用promise
3.手写forEach