JavaScript手寫數組經常使用函數

前言


在開發過程當中,咱們經常使用數組的一些 api相關操做,其中包含 forEachfilterfindfindIndexmapsomeeveryreducereduceRight等函數方法。api

今天,咱們試試手寫這些函數,實現數組這些函數方法。爲了方便,直接在數組原型對象prototype上擴展。數組

閱讀三連:點贊(👍)、關注(😍)、收藏(📝)。

本文 Githab 已上傳,更多往期文章已分類整理。函數

目錄


  • forEach 函數
  • filter 函數
  • find 函數
  • findIndex 函數
  • fill 函數
  • map 函數
  • some 函數
  • every 函數
  • reduce 函數
  • reduceRight 函數

正文


參數說明oop

callbackFn 回調函數
thisArg 執行 callbackFn 時使用的 this 值
currentValue 數組中正在處理的元素
index 當前索引
array 源數組
accumulator 累加器
initialValue reduce reduceRight 第一次調用 callbackFn 函數時的第一個參數的值默認值
element 本身實現的 this 對象

forEach 函數


語法: arr.forEach(callbackFn(currentValue [, index [, array]])[, thisArg])
方法功能: 對數組的每一個元素執行一次給定的函數。測試

返回: undefined。
自定義函數:myForEach。this

Array.prototype.myForEach = function(callbackFn, thisArg) {
    if (typeof callbackFn !== 'function') throw ('callbackFn參數必須是函數');
    let element = this,
        len = element && element.length || 0;
    if (!thisArg) thisArg = element;
    for (let index = 0; index < len; index++) {
        callbackFn.call(thisArg, element[index], index, element);
    }
};

filter 函數


語法: var newArray = arr.filter(callbackFn(currentValue[, index[, array]])[, thisArg])
方法功能: 建立一個新數組, 其包含經過所提供函數實現的測試的全部元素。prototype

返回: 一個新的、由經過測試的元素組成的數組,若是沒有任何數組元素經過測試,則返回空數組。
自定義函數:myFilter。code

Array.prototype.myFilter = function(callbackFn, thisArg) {
    if (typeof callbackFn !== 'function') throw ('callbackFn參數必須是函數');
    let element = this,
        len = element && element.length || 0,
        result = [];
    if (!thisArg) thisArg = element;
    for (let index = 0; index < len; index++) {
        if (callbackFn.call(thisArg, element[index], index, element)) result.push(element[index]);
    }
    return result;
};

find 函數


語法:arr.find(callbackFn[, thisArg])
方法功能: 返回數組中知足提供的測試函數的第一個元素的值。不然返回 undefined。對象

返回: 數組中第一個知足所提供測試函數的元素的值,不然返回 undefined。
自定義函數:myFind。索引

Array.prototype.myFind = function(callbackFn, thisArg) {
    if (typeof callbackFn !== 'function') throw ('callbackFn參數必須是函數');
    let element = this,
        len = element && element.length || 0;
    if (!thisArg) thisArg = element;
    for (let index = 0; index < len; index++) {
        if (callbackFn.call(thisArg, element[index], index, element)) {
            return element[index];
        }
    }
    return
}

findIndex 函數


語法: arr.findIndex(callbackFn[, thisArg])
方法功能: 返回數組中知足提供的測試函數的第一個元素的值。不然返回 undefined。

返回: 數組中經過提供測試函數的第一個元素的索引。不然,返回-1。
自定義函數:myFindIndex。

Array.prototype.myFindIndex = function(callbackFn, thisArg) {
    if (typeof callbackFn !== 'function') throw ('callbackFn參數必須是函數');
    let element = this,
        len = element && element.length || 0;
    if (!thisArg) thisArg = element;
    for (let index = 0; index < len; index++) {
        if (callbackFn.call(thisArg, element[index], index, element)) return index;
    }
    return -1;
}

fill函數


語法: arr.fill(value[, start[, end]])
方法功能: 用一個固定值填充一個數組中從起始索引到終止索引內的所有元素。不包括終止索引。

返回: 返回替換的值,原數組發生改變。
自定義函數:myFill。

Array.prototype.myFill = function(value, start = 0, end) {
    let element = this,
        len = element && element.length || 0;
    end = end || len;
    let loopStart = start < 0 ? 0 : start, // 設置循環開始值
        loopEnd = end >= len ? len : end; // 設置循環結束值

    for (; loopStart < loopEnd; loopStart++) {
        element[loopStart] = value;
    }
    return element;
}

map 函數


語法: var new_array = arr.map(function callbackFn(currentValue[, index[, array]]) {// Return element for new_array }[, thisArg])
方法功能: 建立一個新數組,其結果是該數組中的每一個元素是調用一次提供的函數後的返回值。

返回: 測試數組中是否是至少有1個元素經過了被提供的函數測試。它返回的是一個Boolean類型的值。 一個由原數組每一個元素執行回調函數的結果組成的新數組。
自定義函數:myMap。

Array.prototype.myMap = function(callbackFn, thisArg) {
    if (typeof callbackFn !== 'function') throw ('callbackFn參數必須是函數');
    let element = this,
        len = element && element.length || 0,
        result = [];
    if (!thisArg) thisArg = element;
    for (let index = 0; index < len; index++) {
        result[index] = callbackFn.call(thisArg, element[index], index, element);
    }
    return result;
}

some 函數


語法: arr.some(callbackFn(currentValue[, index[, array]])[, thisArg])
方法功能: 測試數組中是否是至少有1個元素經過了被提供的函數測試。它返回的是一個Boolean類型的值。

返回: 數組中有至少一個元素經過回調函數的測試就會返回true;全部元素都沒有經過回調函數的測試返回值纔會爲false。
自定義函數:mySome。

Array.prototype.mySome = function(callbackFn, thisArg) {
    if (typeof callbackFn !== 'function') throw ('callbackFn參數必須是函數');
    let element = this,
        len = element && element.length || 0;
    if (!thisArg) thisArg = element;
    for (let index = 0; index < len; index++) {
        if (callbackFn.call(thisArg, element[index], index, element)) return true;
    }
    return false;
}

every 函數


語法: arr.every(callbackFn(currentValue[, index[, array]])[, thisArg])
方法功能:測試一個數組內的全部元素是否都能經過某個指定函數的測試。它返回一個布爾值。

返回: 若是回調函數的每一次返回都爲 true 值,返回 true,不然返回 false。
自定義函數:myEvery。

Array.prototype.myEvery = function(callbackFn, thisArg) {
    if (typeof callbackFn !== 'function') throw ('callbackFn參數必須是函數');
    let element = this,
        len = element && element.length || 0;
    if (!thisArg) thisArg = element;
    for(let index = 0; index < len; index++) {
        if (!callbackFn.call(thisArg, element[index], index, element)) return false;
    }
    return true;
}

reduce 函數


語法:
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
方法功能:對數組中的每一個元素執行一個由您提供的reducer函數(升序執行),將其結果彙總爲單個返回值。

返回: 函數累計處理的結果。
自定義函數:myReduce。

Array.prototype.myReduce = function(callbackFn, initialValue) {
    if (typeof callbackFn !== 'function') throw ('callbackFn參數必須是函數');
    let element = this,
        len = element.length || 0,
        index = 0,
        result;
    if (arguments.length >= 2) {
        result = arguments[1];
    } else {
        while (index < len && !(index in element)) index++;
        if (index >= len) throw new TypeError('Reduce of empty array ' + 'with no initial value');
        result = element[index++];
    }

    while (index < len) {
        if (index in element) result = callbackFn(result, element[index], index, element);
        index++;
    }
    return result;
}

reduceRight 函數


語法: arr.reduceRight(callback(accumulator, currentValue[, index[, array]])[, initialValue])
方法功能: 接受一個函數做爲累加器(accumulator)和數組的每一個值(從右到左)將其減小爲單個值。

返回: 執行以後的返回值。
自定義函數:myReduceRight。

Array.prototype.myReduceRight = function(callbackFn, initialValue) {
    if (typeof callbackFn !== 'function') throw ('callbackFn參數必須是函數');
    let element = this,
        len = element.length || 0,
        index = len - 1,
        result;
    if (arguments.length >= 2) {
        result = arguments[1];
    } else {
        while (index >= 0 && !(index in element)) {
            index--;
        }
        if (index < 0) {
            throw new TypeError('reduceRight of empty array with no initial value');
        }
        result = element[index--];
    }
    for (; index >= 0; index--) {
        if (index in element) {
            result = callbackFn(result, element[index], index, element);
        }
    }
    return result;
}

最後


若是喜歡或對你有用,那就點個讚唄(👍👍👍)! (╯ε╰)(╯ε╰)(╯ε╰)。

相關文章
相關標籤/搜索