How to solve the jshint error `Don't make functions within a loop.` with jquery $.grep

本秂侑毒 提交于 2019-12-24 04:59:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!