JS 數組對象如何使用Array.reduce

數組對象如何使用reduce將每個對象的屬性累加求和

需求: 現有一個數組對象,[{date:‘2020-03-29 12:12’, count: 12}, {date: ‘2020-03-28 13:12’, count: 23}], 需要求所有天數的sum(count)
使用技術: Array.reduce()

/*
** reduce 函數接收四個參數, 分別是total,currentValue, index,arr
** total 必需。初始值, 或者計算結束後的返回值。
** currentValue 必需。當前元素
** currentIndex 可選。當前元素的索引
** arr 可選。當前元素所屬的數組對象。
*/
const dateArray = [
	{date:'2020-03-29 12:12', count: 12},
	{date: '2020-03-28 13:12', count: 23}
];
const numberPattern = /^[+-]?\d+(\.\d+)?$/;
const totalCount = dateArray .reduce((total, currentValue, currentIndex, arr) => {
                    const countMatched = numberPattern.exec(currentValue.count);  // 加這一步的原因是怕某些數據可能還包含其他文字,導致不能累加, 所以加上這一步將數字匹配出來
                    let count = 0; // 這裏指的是count不是Number, 就默認爲0
                    if (countMatched) {
                        count = parseFloat(countMatched[0]); // 這裏是指將match到的數字(字符串)轉化爲Number類型
                    }
                    return total + count;
                }, 0);
               

【後續】
這裏有一點需要注意的是parseFloat()的用法,它的參數一定要是以數字開頭的字符串(當然直接是Number類型更好),否則parseFloat的結果就是NaN.比如: parseFloat(’“1233”’)或者parseFloat(’_11’), 這樣就不行,結果爲NaN. 但是*parseFloat(’.11’)*這樣是可以的,返回0.11. 這也是我在處理數據的時候遇到踩的一些坑啦, 希望大家不要遇到哦!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章