国产成人精品18p,天天干成人网,无码专区狠狠躁天天躁,美女脱精光隐私扒开免费观看

javascript數組includes、reduce的基本使用

發(fā)布時(shí)間:2021-08-17 12:16 來(lái)源: 閱讀:0 作者:天行無(wú)忌 欄目: JavaScript 歡迎投稿:712375056

目錄

    前言

    在過(guò)去的幾年中,JavaScript語(yǔ)言進(jìn)行了多次更新。為了跟上技術(shù)更新的腳步,時(shí)刻保持一顆學(xué)習的心。趁著(zhù)休息的時(shí)間學(xué)習熟悉一下數組的includes、reduce的使用。

    Array.prototype.includes

    ES7添加對此方法的支持,includes() 方法用來(lái)判斷一個(gè)數組是否包含一個(gè)指定的值的元素,并返回布爾值true或false,如果包含則返回 true,否則返回 false。

    語(yǔ)法

    arr.includes(valueToFind[, fromIndex])

    參數

    • valueToFind(必須):需要查找的元素值,比較字符串和字符時(shí)是區分大小寫(xiě)。
    • fromIndex(可選):從數組 fromIndex 索引處開(kāi)始查找 valueToFind。
      • 負數 ,則按升序從 array.length + fromIndex 的索引開(kāi)始搜 (即使從末尾開(kāi)始往前跳 fromIndex 的絕對值個(gè)索引,然后往后搜尋)。
      • 默認值為 0。

    返回值

    包含則返回 true,否則返回 false。

    實(shí)例

    // ES5 Code
    const numbers = ["一", "二", "三", "四"];
    console.log(numbers.indexOf("一") > -1); // true
    console.log(numbers.indexOf("六") > -1); // false
    
    // ES7 Code
    console.log(numbers.includes("一")); // true
    console.log(numbers.includes("六")); // false
    
    console.log(numbers.includes("一",1)); // false,從數組索引為`1`往后找
    console.log(numbers.includes("一", -3)); // true,從 `array.length + fromIndex` 的索引開(kāi)始完后找,跟上面從索引為1開(kāi)始等效
    

    使用 includes 方法可以使代碼簡(jiǎn)短易懂。include 方法在比較值時(shí)也很方便,如下代碼。

    // 過(guò)去
    const day = "星期二";
    if (day === "星期二" || day === "星期三" || day === "星期四") {
        console.log(day);
    }
    
    // 現在
    if (["星期二", "星期三", "星期四"].includes(day)) {
        console.log(day);
    }
    

    Array.prototype.reduce

    reduce() 方法對數組中的每個(gè)元素執行reducer函數(升序執行),將其結果匯總為單個(gè)返回值。

    語(yǔ)法

    Array.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

    為數組中的每一個(gè)元素依次執行callback函數,不包括數組中被刪除或從未被賦值的元素。

    參數

    • callback(必須):執行數組中每個(gè)值 (如果沒(méi)有提供 initialValue則第一個(gè)值除外)的reducer函數,包含四個(gè)參數
      • accumulator(必須):累計器累計回調的返回值; 它是上一次調用回調時(shí)返回的累積值,初始值可以通過(guò)initialValue定義,默認為數組的第一個(gè)元素值,累加器將保留上一個(gè)操作的值,就像靜態(tài)變量一樣
      • currentValue(必須):數組中正在處理的元素
      • index(可選):數組中正在處理的當前元素的索引。 如果提供了initialValue,則起始索引號為 0,否則從索引 1 起始。
        注意:如果沒(méi)有提供 initialValue,reduce 會(huì )從索引 1 的地方開(kāi)始執行 callback 方法,跳過(guò)第一個(gè)索引。如果提供 initialValue,從索引 0 開(kāi)始。
      • array(可選):調用 reduce() 的數組
    • initialValue(可選):作為第一次調用 callback 函數時(shí)的第一個(gè)參數的值。 如果沒(méi)有提供初始值,則將使用數組中的第一個(gè)元素。 在沒(méi)有初始值的空數組上調用 reduce 將報錯。

    返回值

    函數累計處理的結果。

    實(shí)例

    const arrNumbers = [1, 2, 3, 4, 5];
    const reduceNumbers = (arrayNumbers, accumulatorInitVal = false) => {
        const reduceCallback = (accumulator, currentVal, currentIndex) => {
            console.log(`當前索引:${currentIndex}`);
            return accumulator + currentVal;
        };
        return accumulatorInitVal
            ? arrayNumbers.reduce(reduceCallback, accumulatorInitVal)
            : arrayNumbers.reduce(reduceCallback);
    };
    
    console.log(reduceNumbers(arrNumbers)); // 15,累計器初始值為數組的第一個(gè)元素的值1
    console.log(reduceNumbers(arrNumbers, 10)); // 25,累計器初始值為10
    

    console.log(當前索引:${currentIndex}),是為了更加直觀(guān)的看到索引值。

    第一次未定義初始值輸出如下:

    當前索引:1
    當前索引:2
    當前索引:3
    當前索引:4

    第二次定義了累計器初始值輸出如下:

    當前索引:0
    當前索引:1
    當前索引:2
    當前索引:3
    當前索引:4

    接下來(lái)我們來(lái)看一個(gè)奇葩需求,出于某種原因,需要一個(gè)包含所有用戶(hù)全名的新數組(他們的姓,加上他們的名字),但只有當他們是20多歲,并且他們的全名是3個(gè)字的時(shí)候才需要。不要問(wèn)我們?yōu)槭裁葱枰@么奇葩的數據子集,產(chǎn)品經(jīng)理問(wèn)了,我們很樂(lè )意幫忙^_^

    const users = [
        {
            firstName: "堅",
            lastName: "孫",
            age: 37,
        },
        {
            firstName: "策",
            lastName: "孫",
            age: 21,
        },
        {
            firstName: "葛亮",
            lastName: "諸",
            age: 28,
        },
        {
            firstName: "備",
            lastName: "劉",
            age: 44,
        },
        {
            firstName: "統",
            lastName: "龐",
            age: 22,
        },
        {
            firstName: "維",
            lastName: "姜",
            age: 19,
        },
        {
            firstName: "伯溫",
            lastName: "劉",
            age: 22,
        },
    ];
    const getFullName = (user) => `${user.lastName}${user.firstName}`;
    const filterByAge = (user) => user.age >= 20 && user.age < 30;
    
    // 常規實(shí)現
    const getFilterResult = users
        //  第一步篩選年齡20-30之間的用戶(hù)
        .filter((user) => filterByAge(user))
        //  拼接全名
        .map((user) => getFullName(user))
        //  篩選
        .filter((fullName) => fullName.length === 3);
    
    console.log(getFilterResult);   // [ '諸葛亮', '劉伯溫' ]
    
    // 迭代方式實(shí)現
    const iterationsFilterResult = (arrayResult, currentUser) => {
        const fullname = getFullName(currentUser);
        if (filterByAge(currentUser) && fullname.length === 3) {
            arrayResult.push(fullname);
        }
        return arrayResult;
    };
    console.log(users.reduce(iterationsFilterResult, []));  // [ '諸葛亮', '劉伯溫' ]
    

    總結

    到此這篇關(guān)于javascript數組includes、reduce基本使用的文章就介紹到這了,更多相關(guān)javascript數組includes、reduce內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

    免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。

    FREE性丰满HD毛多多| 亚洲制服无码一区二区三区| 国产超帅GAYCHINA男同| 青青草无码免费一二三区| 亚洲精品国偷自产在线99人热| JAPAN黑人极大黑炮|