map、filter、reduce函數的使用

一、filter() 做用:過濾

        // 一、篩選出大於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)

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

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

三、reduce() 做用:對數組中的元素進行彙總

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

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

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

一、篩選出大於30的數。數組

二、把數組元素乘2app

三、把數組元素彙總函數

    <script> let vm = new Vue({ el: '#app', data: () => ({}), methods: {}, }) // 對下面數組進行以下操做 一、二、3

        /* 一、篩選出大於30的數。 二、把數組元素乘2 三、把數組元素彙總 */ const array = [10, 20, 30, 40, 50, 60, 70, 80] // 一、篩選出大於30的數。
// 普通寫法 let newArray = array.filter(function (k) { return k > 30 }) // 二、把數組元素乘2 //把數組中的每一個元素做爲變量傳進去 let newArray2 = newArray.map(function (n) { return n * 2 }) console.log(newArray2) //三、把數組元素相加 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)
相關文章
相關標籤/搜索