ts-对象数组reduce-数组转对象数组
将字符串数组转化成{name:xxx,count:xxx}[]数组的代码
#定义数据类型
interface CartInfo{
name:string,
count:number
}
let rawItemArray:string[] = ["aa", "aa", "bb", "cc"]
let cartArray = rawItemArray.reduce((resultArray:CartInfo[], curItem:string):CartInfo[]=>{
let existingItem = resultArray.find(it => it.name === item)
if(!existingItem){
resultArray.push({name:item, count:1})
}else{
existingItem.count += 1
}
return resultArray
},[])
reduce是js中数组的数据处理方法
- array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
- total:必需。初始值, 或者计算结束后的返回值。
- currentValue:必需。当前元素
- currentIndex:可选。当前元素的索引
- arr:可选。当前元素所属的数组对象。
- initialValue:可选。传递给函数的初始值
计算数组中元素的和
菜鸟教程(runoob.com)
点击按钮后对数组元素进行四舍五入并计算总和。
数组元素之和: