2016-12-25 46 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