在本教程中,你将学习javascript/typescript中的数组缩减方法,以及如何在react应用中把数组对象缩减为单一数值的例子。
Reduce 该方法是javascript数组中的一个方法,用于减少数组中的元素数量。
javascript/typescript中的数组缩减功能
下面是一个语法
array.reduce(function(accumalator, currentValue, currentIndex, array), initialValue)
reduce函数从一个数组中只返回一个值
例如,你有一个数字数组。
让我们来看看如何用数组的reduce函数对这个数组的值进行求和。
const numberArray = [3,1,8,0,10,20];
const total = numberArray.reduce(
(previousValue, currentValue, index)=>previousValue+currentValue,
0);
console.log(total);
reduce函数会对每个数组执行回调
React数组缩减示例
在这个例子中,我们有一个对象的数组,每个对象都包含id和mark。
让我们找出一个对象的标记字段的总和:
- 在数组中声明了对象的数组
- Reduce迭代一个数组并应用这个方法,这将迭代出单个值
- Reduce有一个回调,接受前值和当前值
- 返回前值和当前值的总和
下面是一个将对象的数组减少为单值的例子
import React from "react";
import "./style.css";
export default class App extends React.Component {
students = [
{
id: "11",
marks: 31
},
{
id: "12",
marks: 80
},
{
id: "3",
marks: 98
}
];
render() {
let total = this.students.reduce(function(prev, current) {
return prev + +current.marks;
}, 0);
return Total Marks, {total};
}
}