[英]forEach array function in javascript
I have a method code like below. 我有下面的方法代码。
static transformModel(control: AbstractControl,companyId:number):aDTO[]
{
let finalRequestObj: aDTO[] = new Array();
let request: aDTO;
let counter: number = 0;
let questionArray = [1,2,3,4,5,6,7];
questionArray.forEach( num =>{
counter= counter+1;
request={
userSeqId:0,//should be updated on server side
companyId: companyId,
questionId : counter,
versionNumber : eueVersion,
answer : findAnswer(counter,control),
confirmTimeStr : "",
screen : SCREEN
};
if(request.answer) {
finalRequestObj.push(request);
}
}
)
return finalRequestObj;
}
In above method how can I not use counter
variable and use the questionArray
values to assign to questionId
inside request object? 在上面的方法中,我如何不使用
counter
变量并使用questionArray
值将其分配给请求对象中的questionId
?
The forEach array method has a second parameter that gets passed to it that represents the index of each element: forEach数组方法有第二个参数传递给它,该参数表示每个元素的索引:
questionArray.forEach( (num, counter) =>{
request={
userSeqId:0,//should be updated on server side
companyId: companyId,
questionId : counter,
versionNumber : eueVersion,
answer : findAnswer(counter,control),
confirmTimeStr : "",
screen : SCREEN
};
if(request.answer) {
finalRequestObj.push(request);
}
}
)
If you want to use the values inside the array, just use the value num
provided by forEach
, like this: 如果要使用数组中的值 ,只需使用
forEach
提供的num
值,如下所示:
questionArray.forEach( num =>{
request={
// ...
questionId : num,
// ...
};
//...
}
)
On the other hand if you want to use something like an auto-incremental value taking the array as reference, use the value index
provided by forEach
as second argument, like this: 另一方面,如果要使用像自动增量值这样的东西作为数组的引用,请使用
forEach
提供的值index
作为第二个参数,如下所示:
questionArray.forEach( (num, index) =>{
request={
// ...
questionId : index,
// ...
};
//...
}
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.