es5實現map/filter

// ES5循環循環實現filter數組

const selfFilter = function (fn, context) {

    let arr = Array.prototype.slice.call(this)

    let filteredArr = []

    for (let i = 0; i < arr.length; i++) {

        if(!arr.hasOwnProperty(i)) continue;

         fn.call(context, arr[i], i, this) && filteredArr.push(arr[i])

    }

    return filteredArr

}

 

 

 

// ES5循環實現mapapp

const selfMap = function (fn, context) {

    let arr = Array.prototype.slice.call(this)

    let mappedArr = []

    for (let i = 0; i < arr.length; i++) {

        // 判斷稀疏數組的狀況

        if (!arr.hasOwnProperty(i)) continue;

        mappedArr.push(fn.call(context, arr[i], i, this))

    }

    return mappedArr

}

 

 

// reduce實現mapthis

const selfMap2 = function (fn, context) {

    let arr = Array.prototype.slice.call(this)

    return arr.reduce((pre, cur, index) => {

        return [...pre, fn.call(context, cur, index, this)]

    }, [])

}
相關文章
相關標籤/搜索