如何将嵌套的for循环变量从一个函数传递给另一个函数?

时间:2019-12-18 22:12:19

标签: typescript parameter-passing nested-loops

我在函数中使用嵌套的for循环。我试图将变量i和变量j整体作为对象传递给另一个函数,但是会引发错误。

public getProductCodes(
   productEvent,
   result,
   messagePublishService: MessagePublishService,
 ) {
   const splitCodes = productEvent.productCodes.split(',');


   for (let i = 0; i < result.length; i++) {
     for (let j = 0; j < result[i].products.length; j++) {
       if (
         productEvent.productCodes.length !== 0 &&
         productEvent.productCodes !== undefined
       ) {
         this.publishProductCode(
           messagePublishService,
           splitCodes,
           result[i],result[i].products[j],        -------> This is what I am trying to pass it as an object (Not individual variable)
           source,
         );
       } else {
         console.log('No data found');
         return;
       }
     }
   }
 }

 public publishProductCode(
   messagePublishService,
   splitCodes,
   result[i],           
   result[i].products[j],
   source,
 ) {
   for (let k = 0; k < splitCodes.length; k++) {
     if (result[i].products[j].productCode === splitCodes[k]) {
       console.log(
         'Product Codes: ' +
           result[i].products[j].productCode +
           ' Country : ' +
           result[i].country +
           ' Language : ' +
           result[i].language,
       );
     }
   }
 }

1 个答案:

答案 0 :(得分:1)

也许替换掉这个:

public publishProductCode(
   messagePublishService,
   splitCodes,
   result[i],           
   result[i].products[j],
   source,
 ) {

与此:

public publishProductCode(
   messagePublishService,
   splitCodes,
   result,           
   resultProducts,
   source,
 ) {

然后在result[i]中用result[i].products[j]result相应地替换对resultProductspublishProductCode的引用。