# 项目中数组循环的一个优化案例

·  阅读 1177

``````//拆分数组
function splitArray(array:Array<any>,spiltLength:number):Array<any>{
let index:number = 0;
let arrayAfterSplit:Array<any> = [];
while (index<array.length){
arrayAfterSplit.push(array.slice(index,index+=spiltLength))
}
return arrayAfterSplit
}
// 构造数据
function constructRequireData(array:Array<any>,property:string){
let TemporaryArray:Array<any> = [];
return new Promise((resolve,reject)=>{
for (let index = 0; index < array.length; index++) {
//这里可以写一些筛选条件
TemporaryArray.push({
value:array[index][property],
label:array[index][property]
})
}
resolve(TemporaryArray)
})
}
// 获取最终数据
function getFinalData(array:Array<any>):Array<any>{
let resultArr:Array<any>=[];
let splitArrayData:Array<any> = splitArray(array,2);
let promiseArray:Array<any> = [];
for (let index = 0; index < splitArrayData.length; index++) {
promiseArray.push(constructRequireData(splitArrayData[index],'serviceName'))
}
Promise.all(promiseArray).then((result:Array<any>)=>{
resultArr  = result.flat();
})
return resultArr
}
let arr:Array<any> = [
{
serviceName:'demo01',
offeringId:'01'
},
{
serviceName:'demo02',
offeringId:'02'
},
{
serviceName:'demo03',
offeringId:'03'
},
{
serviceName:'demo04',
offeringId:'04'
},
{
serviceName:'demo05',
offeringId:'05'
},
{
serviceName:'demo06',
offeringId:'06'
},
{
serviceName:'demo07',
offeringId:'07'
},
]
getFinalData(arr);复制代码``````

TIME！