简体   繁体   中英

How to return from a function with an array loop and nested forEach loop?

I have a function with nested loops, first is an array loop and inside a forEach loop.

const myFunction = (data: string[][]): boolean => {

  for (const row of data) {
    row.forEach((item, i) => {

      if (!something) {
        return false;
      }
      if (
        !somethingelse
      ) {
        return false;
      }

      return undefined;
    });
  }

  return true;
};

Whenever I return false I would like that myFunction will return false, and only at the end if false wasn't returned, I'd like to return true. However to my understanding since it's nested loops, When I return false, I'm actually breaking out of the loop.

The only solution I thought about is to declare a variable and set it to "false" and then return the result at the end of all loops. However I'm finding that this might not be a good solution since es-lint complains when trying to change variables declared outside of the loop (can cause memory leaks). Is there another way without creating a variable, is there a way to return from a function without solely break out of the loop?

I think for this you could use the.some method on arrays.

const myFunction = (data: string[][]): boolean => {
    const result = data.some(row => 
        row.some((item, i) => {
            if(!something) 
                return false
            else if (!somethingElse)
                return false
            else return true 
      }))
    
    return result
}

This would allow you to iterate through all of the data, if one of the conditions is met to true then the value of result would be true. Else it would be false.

A "for(;;)" loop or a "for of" are options which don't take away your ability to return early.

Another option is to use "find" to return a specific value from the array, or "some" if you only need to return true/false.

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