map、filter、reduce函數的使用


1、filter() 作用:過濾

        // 1、篩選出大於30的數。
        const array = [10, 20, 30, 40, 50, 60, 70, 80] // 普通寫法
        // let newarray = array.filter(function (k) {
        // return k > 30
        // })

        // ES6寫法
        let newarray = array.filter((k) => k > 30) console.log(newarray)

2、map() 作用:便於對數組中的每個元素進行操作

        // 2、把數組元素乘2
        //把數組中的每個元素作為變量傳進去
        let newArray2 = newarray.map(function (n) { return n * 2 }) console.log(newArray2)

3、reduce() 作用:對數組中的元素進行匯總

        //3、把數組中的元素相加
        let newArray3 = array.reduce(function (previousValue, n) { return previousValue + n },0) console.log(newArray3)

******完整代碼******

條件:對數組進行下面三個操作。

1、篩選出大於30的數。

2、把數組元素乘2

3、把數組元素匯總

    <script> let vm = new Vue({ el: '#app', data: () => ({}), methods: {}, }) // 對下面數組進行如下操作 1、2、3

        /* 1、篩選出大於30的數。 2、把數組元素乘2 3、把數組元素匯總 */ const array = [10, 20, 30, 40, 50, 60, 70, 80] // 1、篩選出大於30的數。
// 普通寫法 let newArray = array.filter(function (k) { return k > 30 }) // 2、把數組元素乘2 //把數組中的每個元素作為變量傳進去 let newArray2 = newArray.map(function (n) { return n * 2 }) console.log(newArray2) //3、把數組元素相加 let newArray3 = newArray2.reduce(function (previousValue, n) { return previousValue + n }, 0) console.log(newArray3) </script>
// 鏈式寫法
        let newArray22 = array.filter(function (k) { return k > 30 }).map(function (k) { return k * 2 }).reduce(function (previousValue, k) { return previousValue + k }) console.log(newArray22)

// 箭頭函數寫法
        let newArray333 = array.filter((k) => k > 30).map((k) => k * 2).reduce((previousValue, k) => previousValue + k) console.log(newArray333)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM