如何使用 jquery $.grep 解决 jshint 错误“不要在循环内创建函数。”

2024-02-19

下面的 JavaScript 代码给了我不要在循环内创建函数。 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);
}

我查了一下这个问题,看到其他成员也问了一些类似的问题
如何解决 jslint 错误“不要在循环内创建函数”。 https://stackoverflow.com/questions/3037598/how-to-get-around-the-jslint-error-dont-make-functions-within-a-loop
不要在循环内创建函数 https://stackoverflow.com/questions/10320343/dont-make-functions-within-a-loop

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


来自已登录用户的数据

{
    "user": "MBO",
    "email": "[email protected] /cdn-cgi/l/email-protection",
    "username": "Marcel",
    "photoURL": "url_here",
    "favorites": [13,25,40,56]
}

将函数放在循环之外:

/* 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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 jquery $.grep 解决 jshint 错误“不要在循环内创建函数。” 的相关文章

随机推荐