ES6中數組求和,求平均數方法( reduce )


 應用場景一    計算數組中所有值的總和
var numbers = [3,5,9];
        var sumValue = numbers.reduce(function(sum,number){ //sum2 前兩個數的和
            console.log(sum) //1000 1003 1008
            return sum + number;
        },1000  )  //第一次初始化時用1000 + 數組中的第一項
        console.log(sumValue) //1017
 
將數組中對象的某個屬性抽離到另一個數組中
 var primaryColors = [
            {color:"red"},
            {color:"yellow"},
            {color:"bule"}
        ]
        var colorsArr = primaryColors.reduce(function(arr,primaryColor){
            arr.push(primaryColor.color);
            return arr;
        },[]);
        console.log(colorsArr)    //["red", "yellow", "bule"]

 


免責聲明!

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



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