将字符串数组转化成{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:可选。传递给函数的初始值
计算数组中元素的和
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p>点击按钮后对数组元素进行四舍五入并计算总和。</p>
<button onclick="myFunction()">点我</button>
<p>数组元素之和: <span id="demo"></span></p>
<script>
var numbers = [15.5, 2.3, 1.1, 4.7];
function getSum(total, num) {
return total + Math.round(num);
}
function myFunction(item) {
document.getElementById("demo").innerHTML = numbers.reduce(getSum, 0);
}
</script>
</body>
</html>