用javascript实现Array中fill、every、filter、find、reduce、flat

185 阅读1分钟

实现fill

Array.prototype._fill = function(value, start = 0, end = this.length) {
    if (end > this.length) end = this.length;
    for(let i = start; i < end; i++) {
        this[i] = value;
    }
    return this;
}

实现every

Array.prototype._every = function(callback, thisValue) {
    for(let i = 0; i < this.length; i++) {
        if (!callback.call(thisValue, this[i], i, this)) return false;
    }
    return true;
}

实现some

Array.prototype._some = function(callback, thisValue) {
    for(let i = 0; i < this.length; i++) {
        if (callback.call(thisValue, this[i], i, this)) return true;
    }
    return false;
}

实现filter

Array.prototype._filter = function(callback, thisValue) {
    let res = [];
    for(let i = 0; i < this.length; i++) {
        if (callback.call(thisValue, this[i], i, this)) res.push(this[i])
    }
    return res;
}

实现find

Array.prototype._find = function(callback, thisValue) {
    for(let i = 0; i < this.length; i++) {
        if (callback.call(thisValue, this[i], i, this)) return this[i]
    }
    return;
}

实现findIndex

Array.prototype._find = function(callback, thisValue) {
    for(let i = 0; i < this.length; i++) {
        if (callback.call(thisValue, this[i], i, this)) return i;
    }
    return -1;
}

实现reduce

Array.prototype._reduce = function(callback, initialValue) {
    let start = 0;
    if (initialValue == undefined) initialValue = this[start++];
    for(let i = start; i < this.length; i++) {
        initialValue = callback(initialValue, this[i], i, this);
    }
    return initialValue;
}

实现flat

利用reduce递归遍历即可

Array.prototype._flat = function(deep = 1) {
    return deep > 0
        ? this._reduce((sum, val) => sum.concat(Array.isArray(val)
            ? this._flat.call(val, deep - 1)
            : val), [])
        : this.slice();
}