2012-10-15 33 views
2

以下javascript代碼給我提供了不要在循環中創建函數。錯誤

/* Get the favorite products from the data using the id */ 
productDataCategory[FAVORITES].length = 0/* empty favorites productDataCategory */; 
for (i = 0; i < currentUser.favorites.length; i++) { 
    product = $.grep(productData, function(e){ return e.id === currentUser.favorites[i]; })[0]; 
    productDataCategory[FAVORITES].push(p); 
} 

我看這個問題了,看到其他會員
How to get around the jslint error 'Don't make functions within a loop.'
Don't make functions within a loop

我的問題是,我使用的是$ .grep功能問了一些類似的問題在循環內部查找數組中的產品。
我不知道如何解決這個問題與上述問題的答案。


從登錄的用戶

{ 
    "user": "MBO", 
    "email": "[email protected]", 
    "username": "Marcel", 
    "photoURL": "url_here", 
    "favorites": [13,25,40,56] 
} 
+1

爲什麼不使用只是一個單一的'.grep'(而不是循環數的他們),但檢查'$ .inArray(e.id,currentUser.favorites)!== -1'而不是?你需要用'currentUser.favorites'命令重新排序結果數組嗎? – raina77ow

+0

這是一個非常好的問題。答案是我從來沒有聽說過$ .inArray。這會讓事情變得更快!每個產品使用.grep需要花費很多時間! (我會進入) – Marcel

+0

@ raina77ow'.inArray'只給出位置。它是否一次處理多個位置? (放入一個完整的數組並獲取所有位置)。如果不是這樣,那意味着我需要'.inArray'每個產品+獲得給定位置的數據。 '.grep'似乎是一個更好的解決方案! – Marcel

回答

2

數據放置功能外循環:

/* Get the favorite products from the data using the id */ 
productDataCategory[FAVORITES].length = 0/* empty favorites productDataCategory */; 
var f = function(e){ return e.id === currentUser.favorites[i]; }; 
for (i = 0; i < currentUser.favorites.length; i++) { 
    product = $.grep(productData, f)[0]; 
    productDataCategory[FAVORITES].push(p); 
} 
+0

工作就像一個魅力。 (順便說一句,我看到你編輯你的答案!兩個都在工作,而且目前非常整齊) – Marcel

相關問題