【问题标题】:Iterate through ALL values in a collection before returning true or false在返回 true 或 false 之前遍历集合中的所有值
【发布时间】:2018-01-10 01:57:02
【问题描述】:

我想知道是否有更多“功能性”的方式来做到这一点。意思是,而不是必须做这样的事情:

let flag = true;
[1, 2, 3].forEach(n => if (n > 2) flag = false);
return flag;

我正在寻找更接近这个的东西:

return [1, 2, 3].overEvery(n => n > 2);

我找到的最接近的解决方案是 Array.prototype.every 函数,但它会在返回 false 时终止,不会遍历集合中的其余值。

我不想终止的原因是因为我想遍历表单中的所有字段以显示所有表单错误,然后在表单的 onsubmit 处理程序中返回 true 或 false。

【问题讨论】:

  • Array.prototype.forEach(function(item) { /* each Array item available here as item */ })
  • 除了@connexo 的建议,Array.prototype.reduce() 可能是一个选项。
  • @ChrisRiebschlager every() 立即返回第一个 false 值。
  • 如果您解释了您希望返回值的样子,将会有所帮助。你想要一个布尔数组吗?如果是,简单:[1, 2, 3].map(n => n > 2) 如果不是,那是什么?

标签: javascript html ecmascript-6 lodash


【解决方案1】:

您可以使用Array.filter,如果您为应该失败的元素返回true,它将返回验证失败的元素。

【讨论】:

    【解决方案2】:

    这是另一种方法:

    function a()
    {
      var flag = true;
      [1, 2, 3].forEach(function(value) { if(value > 2) flag = false; });
      return flag;
    }
    
    console.log(a());

    【讨论】:

      【解决方案3】:

      你可以做一个新的原型函数,就像every一样但检查所有记录:

      if (!Array.prototype.everyCheckAll) {
        Array.prototype.everyCheckAll = function(callbackfn, thisArg) {
          'use strict';
          var T, k;
      
          if (this == null) {
            throw new TypeError('this is null or not defined');
          }
      
          // 1. Let O be the result of calling ToObject passing the this 
          //    value as the argument.
          var O = Object(this);
      
          // 2. Let lenValue be the result of calling the Get internal method
          //    of O with the argument "length".
          // 3. Let len be ToUint32(lenValue).
          var len = O.length >>> 0;
      
          // 4. If IsCallable(callbackfn) is false, throw a TypeError exception.
          if (typeof callbackfn !== 'function') {
            throw new TypeError();
          }
      
          // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
          if (arguments.length > 1) {
            T = thisArg;
          }
      
          // 6. Let k be 0.
          k = 0;
      
          // 7. Repeat, while k < len
          var oneFalse = false;
          while (k < len) {
      
            var kValue;
      
            // a. Let Pk be ToString(k).
            //   This is implicit for LHS operands of the in operator
            // b. Let kPresent be the result of calling the HasProperty internal 
            //    method of O with argument Pk.
            //   This step can be combined with c
            // c. If kPresent is true, then
            if (k in O) {
      
              // i. Let kValue be the result of calling the Get internal method
              //    of O with argument Pk.
              kValue = O[k];
      
              // ii. Let testResult be the result of calling the Call internal method
              //     of callbackfn with T as the this value and argument list 
              //     containing kValue, k, and O.
              var testResult = callbackfn.call(T, kValue, k, O);
      
              // iii. If ToBoolean(testResult) is false, return false.
              if (!testResult) {
                oneFalse = true;
              }
            }
            k++;
          }
          return !oneFalse;
        };
      }
      
      function gt2(element, index, array) {
        return element > 2;
      }
      document.write([1,2,3].everyCheckAll(gt2));   // false
      document.write([4,5,6].everyCheckAll(gt2));   // true
      

      【讨论】:

        【解决方案4】:

        使用Array#every,并检查每个数字不大于2。Array#every 的另一个优点是,每当回调返回false,迭代就会停止,并返回结果。

        const flag = [1, 2, 3].every((n) => n <= 2);
        
        console.log(flag);

        【讨论】:

          猜你喜欢
          • 2011-03-20
          • 1970-01-01
          • 1970-01-01
          • 2022-01-18
          • 2013-02-23
          • 2011-01-17
          • 1970-01-01
          • 2017-09-16
          • 1970-01-01
          相关资源
          最近更新 更多