简体   繁体   中英

How to give a function a return value when the return is inside an if statement

I had a function that was initially like this, and worked:

  productGroupPages(): PDF.Page[] {
    const descriptions = {};
    this.areas.forEach(area => descriptions[area.id] = area.description);
    return this.json.engagementAreas.map(area => {
      return this.productGroupPage(area, descriptions[area.id]);
    });
  }

Basically everything isnt wrapped in the for each.

I had to alter to the function as i wanted to go through a for each, to then use an if statement so i would only return values that actually contained a certain value, the result is that my return statement is too early, I cant move it to the end because of the for loop and im struggling to find out how I can get past this,

this new function:

  productGroupPages(): PDF.Page[] {
    const descriptions = {};
    let pages = {};
    console.log('this .json' + JSON.stringify(this.json))
    this.json.engagementAreas.forEach(area => {
      descriptions[area.id] = area.description

      if (area.engagementTypes.length !== 0) {

        return this.json.engagementAreas.map(area => {
          return this.productGroupPage(area, descriptions[area.id]);
        });
      }
    })
  }

I tried creating a variable, an array or object and equaling that to the return value and then returning that near the end of the scope but this wouldnt let me it said the return type was wrong.

Any help would be greatly appreciated.

I think your initial code, with the forEach and map separated was very clean!

The problem with your new code, is that using return inside .forEach() does not make sense in javascript ;) Whenever you return from .forEach() , javascript just ignores the result:

let result = [1,2,3].forEach(x => {
  return x * 2;
});
result // undefined

I think you wanted to only return some area -s, which you can do with array.filter() like this:

productGroupPages(): PDF.Page[] {
  const descriptions = {};
  this.areas.forEach(area => descriptions[area.id] = area.description);
  return this.json.engagementAreas
    .filter(area => area.engagementTypes.length !== 0)
    .map(area => {
      return this.productGroupPage(area, descriptions[area.id]);
    });
}

I hope that is actually what you meant to do, and if so, I hope this works :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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