在 forEach 中使用条件语句时,如何检测是否每个子项都未通过条件

When using conditional statements inside of forEach, how to detect if every child failed the condition?

本文关键字:条件 是否 检测 forEach 语句 何检测      更新时间:2023-09-26

从Firebase DataSnapshot开始,我想要一些东西,用简单的英语来说,"如果所有的孩子都不符合条件,就执行一些东西"。

这是我现在拥有的:

     appleappsRef.on('value', function (allApplesSnapshot){
            allApplesSnapshot.forEach(function (appleSnapshot) {
                if (condition) {
                   //execute code
                } 
            });             
      });   

根据文档,您的 forEach 回调可以返回 true 以取消枚举,而 forEach() 将返回 true 以表示枚举已取消。

这意味着您可以执行以下操作:

appleappsRef.on('value', function (allApplesSnapshot){
  var foundOne = allApplesSnapshot.forEach(function (appleSnapshot) {
    if (condition) {
       return true; // found one, cancel enumeration
    }
  });
  if (!foundOne) {
    // all children failed the condition.
  }
});
if (allApplesSnapshot.every(function (appleSnapshot) { return !condition; }))
    // ...

如果数组的每个元素都满足您传递给它的函数(即,该函数在传递该元素时返回 true),则Array.every返回 true。因此,要测试每个元素是否都不符合条件,则只需否定函数中的条件即可。

请注意,某些浏览器不支持 Array.every ,但每个支持 Array.forEach 的浏览器也应该支持 Array.every

您可以使用

.forEach 使用布尔值来跟踪,如果您发现条件为真:

 appleappsRef.on('value', function (allApplesSnapshot){
        var foundOne = false;
        allApplesSnapshot.forEach(function (appleSnapshot) {
            if (condition) {
               foundOne = true;
            } 
        });             
        if (!foundOne) {
            // all children failed the condition
        }
  });   

好吧,你总是可以循环遍历它,并且在任何时候其中一个子通道以某种方式从方法中突破,否则触发在所有子通道失败时应该触发的方法。在这种情况下,您甚至可以使用布尔值。

例如:创建一个布尔值并将其称为 allChildrenFailed 并将其默认设置为 true。遍历 foreach 循环,如果有任何子循环,请将其更改为 false。然后,只有在 allChildrenFailed 为 true 时,才在循环后触发所需的方法。