1. 程式人生 > 其它 >前端高頻手撕程式碼整理(二)

前端高頻手撕程式碼整理(二)

前端高頻手撕程式碼整理(一)

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)