简体   繁体   English

JavaScript中的forEach数组函数

[英]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,
            // ...
        };
       //...
    }
)

I think what you want is index ( foreach ), then so : 我认为您想要的是索引( foreach ),然后这样:

questionArray.forEach( (num, index) =>{
   // use index variable
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM