【问题标题】:How to stop looping once it found?找到后如何停止循环?
【发布时间】:2017-05-10 09:00:42
【问题描述】:

如果找到three,那么它应该返回true并停止迭代。否则返回 false 如果没有找到。

我正在使用filter() - 使用方法是否错误?

var data = [
  'one',
  'two',
  'three',
  'four',
  'three',
  'five',
];

found = data.filter(function(x) {
   console.log(x);
   return x == "three";
});

console.log(found);

演示:https://jsbin.com/dimolimayi/edit?js,console

【问题讨论】:

标签: javascript


【解决方案1】:

您可以在这种情况下使用array#some

var data = [
  'one',
  'two',
  'three',
  'four',
  'three',
  'five',
];

found = data.some(function(x) {
   return x == "three";
});

console.log(found); // true or false

如果您使用filter,则数组将根据callBack 函数内部返回的真值进行过滤。因此,如果找到任何匹配的含义,如果函数返回值 true,则该特定迭代中的元素将被收集在 array 中,最后将返回数组。

因此,在您的情况下,["three", "theree"] 将作为结果返回。如果您没有任何"three",则将返回一个空数组,在这种情况下,您必须进行额外检查以找到真实值作为结果。

例如:

var res = arr.filter(itm => someCondition);
var res = !!res.length;
console.log(res); //true or false.

所以为了避免过度杀戮的情况,我们使用了 Array#some。

【讨论】:

  • 谢谢你,为了改进你的答案 - 为什么我的解决方案是错误的,我使用了filter
  • 您不必“必须使用” .. 这只是一种可能的方法
  • 其他选择包括Array.find() & Array.includes()
  • @RajaprabhuAravindasamy 感谢兄弟的详细回答! ;)
【解决方案2】:

var data = [
  'one',
  'two',
  'three',
  'four',
  'three',
  'five',
];

for(var i=0;i<data.length;i++){
    console.log(data[i]);
  if(data[i]=="three"){
    var found=data[i];
    break;
  }
}

console.log(found);

【讨论】:

    【解决方案3】:

    您必须返回 false 才能退出函数,但您已经在过滤函数中使用 return 语句,并且不能使用 2 个 return 语句...我想出的另一个解决方案是:

    var data = [
      'one',
      'two',
      'three',
      'four',
      'three',
      'five',
    ];
    
    var filteredData = [];
    
    function a(i,e){
       console.log(e);
    
      if(e == "three"){
        filteredData.push(e);
        return false;
      }
    }
    
    $(data).each(a);
    console.log(filteredData);
    

    这将在它达到“三”时立即爆发,并将其存储在 filtersData 数组中,以便您将来使用它... 希望这会有所帮助....

    【讨论】:

      【解决方案4】:

      直截了当的方法。

          var data = [
            'one',
            'two',
            'three',
            'four',
            'three',
            'five',
          ];
          
          
          found = data.indexOf('three') == -1 ?  false :  true;
          console.log(found);

      【讨论】:

      • indexOf 也将在底层进行循环,传递的值将被置于字符串检查=== 之下。你可以在 ecma 的文档中看到它的算法。
      • @RajaprabhuAravindasamy,感谢您的澄清。引擎盖下的所有循环,似乎。 :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-13
      • 1970-01-01
      • 2018-05-04
      • 2022-01-11
      • 2019-10-17
      • 2021-12-28
      相关资源
      最近更新 更多