简体   繁体   English

可以使用函数在do…while中检查条件是真还是假。

[英]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. 我要检查的是在do处理过所有元素。 The reason is that in the kategoriak array, only one of it's object has szint: 1 . 原因是在kategoriak数组中,只有一个对象具有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. 我要执行此过程,直到每个元素的szint不为0。但这无关紧要。 My question is that what am i doing wrong at the while ? 我的问题是,我是在错误的做什么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. 您可以给while一个函数,但是while不会调用您的函数。 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: 但实际上,这是胡说八道,您只需要使用一个结果为truefalse的表达式,在这种情况下,您要查找的是Array.prototype.some

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. while(...)内部,您定义了一个函数,但未调用它。 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 . 实现此目的的更好方法是使用Array.prototype.some It is a method that returns true when some of the elements satisfy the given function. 当某些元素满足给定功能时,此方法将返回true。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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