如何使用jquery $ .grep解决jshint错误“不要在循环内创建函数". [英] How to solve the jshint error `Don't make functions within a loop.` with jquery $.grep

查看:75
本文介绍了如何使用jquery $ .grep解决jshint错误“不要在循环内创建函数".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下javascript代码为我提供了不要在循环中创建函数.错误

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

我已经查找了这个问题,并看到了其他成员提出的一些类似问题
如何避开jslint错误不要在循环内创建函数."
不要在循环中创建函数

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

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

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.

来自登录用户的数据

{
    "user": "MBO",
    "email": "my@mail.com",
    "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);
}

这篇关于如何使用jquery $ .grep解决jshint错误“不要在循环内创建函数".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆