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);
}

我查看了这个问题,并看到其他成员提出的一些类似问题
如何解决 jslint 错误“不要在循环中创建函数。”
不要在循环中创建函数

我遇到的问题是我在循环中使用 $.grep 函数来查找数组中的产品。
我不知道如何通过上述问题中的答案解决此问题。


来自登录用户的数据

{
    "user": "MBO",
    "email": "my@mail.com",
    "username": "Marcel",
    "photoURL": "url_here",
    "favorites": [13,25,40,56]
}
4

1 回答 1

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);
}
于 2012-10-15T09:11:19.803 回答