数组API

    科技2025-01-06  12

    filter

    Array.prototype.myFilter = function (callback, thisArg) { const res = [] const obj = new Object(this) const len = obj.length >>> 0 // 无符号右移0位,保证为0或正整数 for (let i = 0; i < len; i++) { if (i in obj) { if (callback.call(thisArg, obj[i], i, this)) { res.push(obj[i]) } } } return res }

     

    map

    Array.prototype.myMap = function (callback, thisArg) { const res = [] const obj = new Object(this) const len = obj.length >>> 0 for (let i = 0; i < len; i++) { if (i in obj) { res[i] = callback.call(thisArg, obj[i], i, this) } } return res }

     

    forEach

    Array.prototype.myForEach = function (callback, thisArg) { const obj = new Object(this) const len = obj.length >>> 0 for (let i = 0; i < len; i++) { if (i in obj) { callback.call(thisArg, obj[i], i, this) } } }

     

    reduce

    Array.prototype.myReduce = function (callback, initialValue) { const obj = new Object(this) const len = obj.length >>> 0 let accumulator = initialValue let i = 0 if (accumulator == undefined) { while (i < len && !(i in obj)) { i++ } accumulator = obj[i++] // 未传入初始值,采用数组第一个有效元素 } while (i < len) { if (i in obj) { accumulator = callback.call(undefined, accumulator, obj[i], i, this) } i++ } return accumulator }
    Processed: 0.009, SQL: 8