问题
The following javascript code gives me the Don't make functions within a loop. error
/* 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);
}
I've looked the question up and saw some similar questions asked by other members
How to get around the jslint error 'Don't make functions within a loop.'
Don't make functions within a loop
The problem I have is that I'm using a $.grep function inside the loop to find the product in an array.
I dont know how to resolve this issue with the answers in the above questions.
Data from a logged user
{
"user": "MBO",
"email": "my@mail.com",
"username": "Marcel",
"photoURL": "url_here",
"favorites": [13,25,40,56]
}
回答1:
Put the function outside the loop:
/* 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);
}
来源:https://stackoverflow.com/questions/12892406/how-to-solve-the-jshint-error-dont-make-functions-within-a-loop-with-jquery