如何解决jshint错误`不要使用jquery $ .grep在循环中创建函数

时间:2012-10-15 09:07:42

标签: javascript jquery loops jshint

以下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": "my@mail.com",
    "username": "Marcel",
    "photoURL": "url_here",
    "favorites": [13,25,40,56]
}

1 个答案:

答案 0 :(得分: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);
}