2016-12-25 89 views
6

如果找到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

+1

'滤波器()'方法,运行于**数组中的每一项**该给予功能,并返回该函数返回true的所有项目的阵列; 有用的链接:https://coderwall.com/p/_ggh2w/the-array-native-every-filter-map-some-foreach-methods –

+0

没有错,使用'filter',但你可以使用['。 find()'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)以满足您的要求... http://stackoverflow.com /问题/ 23614054/JavaScript的细微差别 - 的 - myArray的-的foreach-VS-for循环 – Mottie

回答

6

您可以在此背景下使用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内返回truthy值滤波功能。因此,如果任何匹配发现的意义,如果函数具有值true返回,则该特定迭代元件将在一个array收集并终于阵列将被返回。

你的情况 ["three", "theree"]

因此将返回结果。如果您没有任何"three",那么将返回一个空数组。在这种情况下,您必须进行额外的检查才能找到真值。

例如:

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

因此,为了避免,超过杀的情况,我们使用阵列#一些。

+0

谢谢,提高你的答案 - 为什么我的解决方案是错误的,我已经使用'filter' –

+1

你不*“有使用“* ..这只是一种可能的方法 – charlietfl

+0

@我会回来我正在编辑它。给我一分钟。 –

0

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);

+0

不要忘记在代码中定义'found'。 – Mottie

+0

对不起。并感谢你 – ab29007

0

你必须返回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); 

这会尽快突破,因为它击中“三化”,也将其存储在filteredData阵列,因此您可以在将来使用它... 希望这有助于....

0

直截了当的方法。

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

+2

'indexOf'也将循环下引擎盖和传递的值将被放在字符串检查'==='。你可以在ecma的文档中看到它的算法。 –

+1

@RajaprabhuAravindasamy,谢谢澄清。看起来,引擎盖下的所有循环。 :) – sinisake