简体   繁体   中英

It's possible to use a function to check if the condition is true or false in do…while?

Here's my code. What i want to check is that all the elements processed in the do , or not. The reason is that in the kategoriak array, only one of it's object has szint: 1 . But it's possible that this element is at the end of the array. I want to do the process until every element has a szint which is not 0. But it don't matter. My question is that what am i doing wrong at the while ? The code should work, but it's an infinite loop. Any ideas?

 do{ kategoriak.forEach(elem => { elem.child.forEach(child => { kategoriak.forEach(ell => { if(child === ell.id && elem.szint !== 0){ ell.szint = elem.szint + 1 } }) }) }) } while( () => { kategoriak.forEach(elem => { if(elem.szint === 0){ return true } }) return false } ) 

You can give while a function, but while isn't going to call your function. It will regard a function as a truthy value and hence continue endlessly. You'll have to call your function yourself. But really, that is nonsense, you just have to use an expression which results in true or false , in this case Array.prototype.some is what you're looking for:

do {
   ...
} while (kategoriak.some(elem => elem.szint === 0));

(Whether this is the best approach to this problem in the first place I dare not say.)

Inside the while(...) you define a function but not call it. Thus, the function expression itself is the condition, which is always true. You need to also call your function. ie

do{
    ...
} while(
    (() => {
      kategoriak.forEach(elem => {
          if(elem.szint === 0){
              return true
          }
      })
      return false
    })(); // Notice the parentheses we use to call the function
)

An even better way to implement this would be using Array.prototype.some . It is a method that returns true when some of the elements satisfy the given function.

do {
    ...
} while (kategoriak.some(elem => elem.szint === 0))

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