reduce
is an array method in JavaScript that is used to accumulate all elements of the array and ultimately return a single value. It accepts a callback function as a parameter. This callback function can accept four parameters:
- Accumulator: The accumulator is the result of each callback function execution. It accumulates the accumulated value in each iteration.
- Current element: The element currently being processed in the array.
- Current index: The index of the current element in the array.
- Original array:
reduce
The original array of the call.
reduce
There are two forms of methods, one only accepts a callback function, and the other can also accept an initial value as the second parameter.
Here is reduce
a basic usage example of :
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
In this example, we use to sum the elements in an array reduce
. numbers
The initial value 0
is passed to the accumulator, and then the callback function adds the accumulator and the current element on each iteration, resulting in the final sum.
You can also provide no initial value, in which case reduce
the first element of the array will be used as the initial value by default, and iteration will start from the second element. If the array is empty and no initial value is provided, an error will be thrown.
reduce
is very versatile, you can use it to perform various accumulation operations, such as finding the maximum/minimum value, concatenating strings, calculating averages, etc. Depending on your needs, you can write appropriate logic in the callback function to achieve the required functionality.
PS: The following is a writing method used in my code (you can learn about my own notes on 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}
}