简体   繁体   中英

How can i break a for in loop from nested forEach Function in Javascript?

I have a this loops

for (var key in params) {
  if (Array.isArray(params[key])) {
    params[key].every(function(item) {
      let value = something(item.start, item.end);
      if (value === item.start || value == item.end) {
        return false // break
      }
    })
  }
}

When i set return false to stop the every() function i also want to stop the first loop. How can i do that? I tried this:

OUTER_LOOP: for (var key in params) {
  if (Array.isArray(params[key])) {
    params[key].every(function(item) {
      let value = something(item.start, item.end);
      if (value === item.start || value == item.end) {
        return false // break
        break OUTER_LOOP; // not working
      }
    })
  }
}

but it doesn't work in this way... so how can i stop the every() function and the first loop at same time correctly?

You could take Array#some and return true for exit some and use the returned value of some for breaking the loop.

for (var key in params) {
    if (Array.isArray(params[key])) {
        const
            leave = params[key].some(item => {
                let value = something(item.start, item.end);

                // exit condition should return true/truthy value
                // for leaving the outer loop
                return value === item.start || value == item.end;
            });

        if (leave) break;
    }
}

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