简体   繁体   中英

Can you break a loop from a nested function?

I have a for loop which repeats a query function to iterate through an array. Sometimes the query reaches the end of the array before the loop has finished, resulting in multiple undefined returns as the loop continues running the query function.

My current solution is to put a check for undefined inside of the query function, and then break the loop if the query function returns undefined:

const arr = [...];

function query(index, array) {
  if (array[index] == null)
    return
  return array[index];
}

for (let i = 0; i < 10; i++) {
  if (query(i, arr ) === undefined)
    break;
}

Is there a way for me to break the loop immediately from inside of query() to be more efficient? Something like:

function query(index, array) {
  if (array[index] == null)
    break
  return array[index];
}

for (let i = 0; i < 10; i++) {
  query(i, array) // will automatically break if query() says so
}

When I try this the console logs Uncaught SyntaxError: Illegal break statement . I get that this is because the break is occuring within the context of the query() function rather than the loop, but is there a way for me to send the break upwards to be evaluated at the loop level? Or any other way to achieve this?

function query(index, array) {
  if (array[index] == null)
    return false
  return (array[index]);
}

for (let i = 0; i < 10; i++) {
  if (!query(i, arr ))
    break;
}

You can clean the array before the loop:

 let arr = [1, null, 2, 3, 4, 5, 6, null, undefined, false, 0, 0, 10]; arr = arr.filter((a)=>;.a); console.log(arr);

But you can use something like this:

for(let one of array){
    if(!one)continue;
    console.log(one); // there is your function block
}

Here's how I would go about it, I wrote my explanation as comments

function query(index, array) {
  const value = array[index] ?? false; // I'm, checking if the array item is undefined or nullish using the nullish coalescing operator
  if (!value && +value != 0) return; // I'm checking to ensure the item isn't 0, because 0 is also falsy and returning undefined
  return array[index];
}

for (let i = 0; i < 10; i++) {
  const result = query(i, array);
  if (result == undefined) break; // Checking if the function returns undefined and breaking the loop if true
  else console.log(result);
}

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