搜尋
首頁web前端前端問答es6遍歷數組都有什麼方法

es6遍歷數組都有什麼方法

Mar 07, 2022 pm 06:49 PM
es6遍歷數組

es6遍歷陣列的方法:1、使用forEach(),可為陣列中的每個元素呼叫一個函數;2、使用map(),對陣列的每個元素呼叫指定的回呼函數; 3.使用filter(),會呼叫一個回呼函數來過濾數組中的元素,返回所有符合條件的元素;4、使用some(),遍歷數組,以檢測數組中是否存在指定條件的元素;5、使用every(),可判斷數組元素是否都符合條件;6、使用reduce()。

es6遍歷數組都有什麼方法

本教學操作環境:windows7系統、ECMAScript 6版、Dell G3電腦。

ES6常見的陣列遍歷(迭代)方法

  • forEach
  • map
  • filter
  • some
  • every
  • reduce

宣告一個需要遍歷的物件

下面的程式碼都是要引用這個物件的

 let data = {
                code: 1,
                list: [{
                        id: 23,
                        title: "女装1",
                        price: 300
                    },
                    {
                        id: 24,
                        title: "女装2",
                        price: 200
                    },
                    {
                        id: 27,
                        title: "男装1",
                        price: 100
                    },
                    {
                        id: 29,
                        title: "男装2",
                        price: 400
                    },
                    {
                        id: 230,
                        title: "女装3",
                        price: 600
                    },
                    {
                        id: 40,
                        title: "童装1",
                        price: 700
                    }
                ]
            }

forEach

forEach的話不能使用break 與continue語句

    // 有二个参数 第一个参数是数值 第二个参数是索引值 
     data.list.forEach(function(item,index){
    console.log(item,index)
    
 //输出结果是{
//   {id: 23, title: "女装1", price: 300} 0
//  {id: 24, title: "女装2", price: 200} 1
//  {id: 27, title: "男装1", price: 100} 2
//  {id: 29, title: "男装2", price: 400} 3
//  {id: 230, title: "女装3", price: 600} 4
//  {id: 40, title: "童装1", price: 700} 5
//     }
    
     })

map

    //map 映射
    //遍历数据并返回一个新的数组 对数据的处理会返回原先对应的位置

    let arr = [2, 3, 6];
    let newArr = arr.map(function (val, index) {
        // 第一个参数是值 第二个参数是索引值
        console.log(arr)
    })

 **遍歷資料並傳回一個新的陣列對資料的處理會傳回原先對應的位置

 要加入程式碼區塊map 不可以解析同一個區塊級作用域

 {}{}代表不同的區塊級作用域分別在不同里面寫**

// 浅拷贝
// 浅拷贝是指a把值 给了b 当b的值改变 a b 的值同时改变。
{
        let arr = [2, 3, 6];
        let newArr = arr.map(function (index, val) {
            // 第一个参数是索引值 第二个参数是值        })
        console.log(arr)// 0: 2
                        // 1: 3
                         // 2: 6    }
    {
        // 浅拷贝
        // 浅拷贝是指a把值 给了b 当b的值改变 a b 的值同时改变。
        let newArr = data.list.map((item, index) => {
            item.price = item.price * .6
            return item;
        });
        console.log(newArr)//打印的结果价格都是改变的,一样的{
        // 0: {id: 23, title: "女装1", price: 180}
        // 1: {id: 24, title: "女装2", price: 120}
        // 2: {id: 27, title: "男装1", price: 60}
        // 3: {id: 29, title: "男装2", price: 240}
        // 4: {id: 230, title: "女装3", price: 360}
        // 5: {id: 40, title: "童装1", price: 420}
        // }
        console.log(data.list)//同上    }

es6遍歷數組都有什麼方法

輸出結果深拷貝無論a b 值哪一個改變最終結果都不會隨著a b的改變而改變

es6遍歷數組都有什麼方法

//深拷貝2(簡單粗暴)

es6遍歷數組都有什麼方法
es6遍歷數組都有什麼方法

filter 過濾

filter會呼叫一個回呼函數來過濾陣列中的元素,返回符合條件的所有元素

es6遍歷數組都有什麼方法
過濾到價格小於300的列印出來
es6遍歷數組都有什麼方法

##some

作用是偵測數組中是否存在指定條件的元素;若存在指定的元素則傳回的結果是true,若不存在指定的元素則傳回的結果是false

es6遍歷數組都有什麼方法

es6遍歷數組都有什麼方法

every

every方法用來判斷陣列中是否任意一個元素都符合判斷條件,判斷同樣是在回呼函數的函數體內完成,並由回呼函數傳回一個布林值。如果回呼函數在某次傳回了false,則整個every方法傳回false,且結束遍歷。

es6遍歷數組都有什麼方法這個是輸出的資訊

es6遍歷數組都有什麼方法

#reduce 用來實現累加的效果

輸出的總和是sum val(數值)

// reduce 用来实现累加的效果 (常用于写购物车价格的累加)
// 声明一个数组 数组里面放数字 让其里面的数字显示为累加的总和
//  let arr=[200,200,100]
//  let result =arr.reduce((sum,val,index)=>{
//                          200+200 index 
//                          400+100 index
// sum是总加后的和 val是变量里面的值 index为索引值 
//     console.log(sum,val,index)
//     return sum +val;
//  })
//  console.log(result)

es6遍歷數組都有什麼方法

【相關推薦:

javascript影片教學web前端#

以上是es6遍歷數組都有什麼方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
反應的局限性是什麼?反應的局限性是什麼?May 02, 2025 am 12:26 AM

Include:1)AsteeplearningCurvedUetoItsVasteCosystem,2)SeochallengesWithClient-SiderEndering,3)潛在的PersperformanceissuesInsuesInlArgeApplications,4)ComplexStateStateManagementAsappsgrow和5)TheneedtokeEedtokeEedtokeEppwithitsrapideDrapidevoltolution.thereedtokeEppectortorservolution.thereedthersrapidevolution.ththesefactorsshesssheou

React的學習曲線:新開發人員的挑戰React的學習曲線:新開發人員的挑戰May 02, 2025 am 12:24 AM

reactischallengingforbeginnersduetoitssteplearningcurveandparadigmshifttocoment oparchitecent.1)startwithofficialdocumentationforasolidFoundation.2)了解jsxandhowtoembedjavascriptwithinit.3)

為React中的動態列表生成穩定且獨特的鍵為React中的動態列表生成穩定且獨特的鍵May 02, 2025 am 12:22 AM

ThecorechallengeingeneratingstableanduniquekeysfordynamiclistsinReactisensuringconsistentidentifiersacrossre-rendersforefficientDOMupdates.1)Usenaturalkeyswhenpossible,astheyarereliableifuniqueandstable.2)Generatesynthetickeysbasedonmultipleattribute

JavaScript疲勞:與React及其工具保持最新JavaScript疲勞:與React及其工具保持最新May 02, 2025 am 12:19 AM

javascriptfatigueinrectismanagbaiblewithstrategiesLike just just in-timelearninganning and CuratedInformationsources.1)學習whatyouneedwhenyouneedit

使用USESTATE()掛鉤的測試組件使用USESTATE()掛鉤的測試組件May 02, 2025 am 12:13 AM

tateractComponents通過theusestatehook,使用jestandReaCtTestingLibraryToSigulationsimintionsandIntractions and verifyStateChangesInTheUI.1)underthecomponentAndComponentAndComponentAndConconentAndCheckInitialState.2)模擬useruseruserusertactionslikeclicksorformsorformsormissions.3)

React中的鑰匙:深入研究性能優化技術React中的鑰匙:深入研究性能優化技術May 01, 2025 am 12:25 AM

KeysinreactarecrucialforopTimizingPerformanceByingIneFefitedListupDates.1)useKeyStoIndentifyAndTrackListelements.2)避免使用ArrayIndi​​cesasKeystopreventperformansissues.3)ChooSestableIdentifierslikeIdentifierSlikeItem.idtomaintainAinainCommaintOnconMaintOmentStateAteanDimpperperFermerfermperfermerformperfermerformfermerformfermerformfermerment.ChosestopReventPerformissues.3)

反應中的鍵是什麼?反應中的鍵是什麼?May 01, 2025 am 12:25 AM

ReactKeySareUniqueIdentifiers usedwhenrenderingListstoimprovereConciliation效率。 1)heelPreactrackChangesInListItems,2)使用StableanDuniqueIdentifiersLikeItifiersLikeItemidSisRecumended,3)避免使用ArrayIndi​​cesaskeyindicesaskeystopreventopReventOpReventSissUseSuseSuseWithReRefers和4)

反應中獨特鍵的重要性:避免常見的陷阱反應中獨特鍵的重要性:避免常見的陷阱May 01, 2025 am 12:19 AM

獨特的keysarecrucialinreactforoptimizingRendering和MaintainingComponentStateTegrity.1)useanaturalAlaluniqueIdentifierFromyourDataiFabable.2)ifnonaturalalientedifierexistsistsists,generateauniqueKeyniqueKeyKeyLiquekeyperaliqeyAliqueLiqueAlighatiSaliqueLiberaryLlikikeuuId.3)deversearrayIndi​​ceSaskeyseSecialIndiceSeasseAsialIndiceAseAsialIndiceAsiall

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具