reduce
是 JavaScript 中的一个数组方法,用于对数组的所有元素进行累积操作,最终返回一个单一的值。它接受一个回调函数作为参数,这个回调函数可以接受四个参数:
reduce
的原始数组。reduce
方法有两种形式,一种只接受回调函数,另一种还可以接受一个初始值作为第二个参数。
以下是 reduce
的基本用法示例:
const numbers = [1, 2, 3, 4, 5];
// 使用 reduce 对数组中的元素求和
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0); // 初始值为 0
console.log(sum); // 输出 15,因为 1 + 2 + 3 + 4 + 5 = 15
在这个示例中,我们使用 reduce
对 numbers
数组中的元素进行求和。初始值 0
被传递给累积器,然后回调函数在每次迭代中将累积器和当前元素相加,最终得到总和。
你还可以不提供初始值,此时 reduce
会默认使用数组的第一个元素作为初始值,然后从第二个元素开始迭代。如果数组为空且没有提供初始值,则会抛出错误。
reduce
的用途非常广泛,你可以使用它来执行各种累积操作,例如查找最大/最小值、拼接字符串、计算平均值等。根据你的需求,你可以在回调函数中编写适当的逻辑来实现所需的功能。
PS:下面是我代码里用到的一种写法(自己写appsmitch的笔记,可以了解下)
const columns = inputData.fieldSource.reduce((prev:any,next:any,index:number)=>{
const { shouId,type } = next
prev[shouId] = {
id:shouId,
label:shouId,
index:index,
columnType:type,
width:100,
}
return prev;
},{}
)
这里 fieldSource格式为
fieldSource:[
{
shouId:'code',
type:'TEXTBOX'
},
{
shouId:'delect',
type:'TEXTBOX',
}
]
///
生成的结果为:
console.log(columns )
columns ={
code:{id:'code',label:'code',index:0,columnType:'TEXTBOX',width:100},
delect:{id:'delect',label:'delect',index:1,columnType:'TEXTBOX',width:100}
}