2015-09-17 69 views
0

我有一個簡單的數組:提取值當條件滿足

var c = [4,5,6,7,8,9,10,11,12]; 

我通過數組迭代,試圖返回的符合條件的值:

$.each(c, function() { 
    // I need to pass each value from the array as the 
    // last argument in the function below 
    var p = get_shutter_price(width, height, c); 
    if (p > 0) { 
     // Return the value from the array which allowed the condition to be met 
     console.log(c); 
    } 
}); 

這確實不按預期工作,因爲整個數組正在傳遞到函數中。

如何返回數組中允許條件滿足的值表單?

例如,如果從陣列的數量是一個返回大於一個價格,然後返回。

+0

所有的值,還是隻有第一個符合條件? – Yoshi

回答

2

只要你想從c符合條件的所有值,只需filter

var c = [4,5,6,7,8,9,10,11,12]; 

var conditionsMet = c.filter(function (value) { 
    return 0 < get_shutter_price(width, height, value); 
}); 

conditionsMet[0]則是第一個滿足的條件。

+1

偉大的方法!我認爲你的意思是'conditionsMet [0]',但是我認爲如果沒有元素返回,你最終會得到'[]',所以你必須在嘗試檢索'[0]'之前運行一個測試。 – PeterKA

+0

謝謝,這是很好,乾淨,正是我所需要的 – Und3rTow

+0

@PeterKA你是對的,當然在這兩種情況下。儘管關於後者,但我傾向於不在SO上包括這樣的測試,因爲它們每次都或多或少需要。這樣就會讓答案混亂。 – Yoshi

0

根據the docs您可以在回調函數中使用兩個參數,第一個是您正在迭代的項目的索引,第二個是項目的值。

$.each(c, function(index, val) { 
    // I need to pass each value from the array as the 
    // last argument in the function below 
    var p = get_shutter_price(width, height, val); 
    if (p > 0) { 
     // Return the value from the array which allowed the condition to be met 
     console.log(c=val); 
    } 
}); 
+1

如果你解釋什麼是錯誤的,以及如何解決它,而不是僅僅鋪設一些代碼,那麼這將是一個更好的答案。 – Andy

+0

謝謝,我正在研究它,只花了一分鐘時間查看文檔。 – tcigrand

0

使用this代替c,通過當前迭代值,你是,當你使用c整個陣列被傳遞100%正確的,所以使用this通過正被迭代的當前項 -

$.each(c, function() { 
    // I need to pass each value from the array as the 
    // last argument in the function below 
    var p = get_shutter_price(width, height, this); 
    if (p > 0) { 
     // Return the value from the array which allowed the condition to be met 
     console.log(this); 
    } 
}); 
0
jQuery.each(c, function(index, item) { 
// do something with `item` 
}); 

在你的代碼錯過了通過索引和項目作爲參數傳遞給函數(這裏指數是可選的)

1

據我所知正確你需要array.prototype.filter方法來過濾你的數組取決於條件。

var b = c.filter(function(val) { 
    return val > 0; 
}); 
你的情況

只是把你的情況是這樣的:

var b = c.filter(function(val) { 
    return get_shutter_price(width, height, val) > 0; 
}); 

這將返回與此條件的新數組。