【问题标题】:How to solve the jshint error `Don't make functions within a loop.` with jquery $.grep如何使用 jquery $.grep 解决 jshint 错误“不要在循环中创建函数。”
【发布时间】:2012-10-05 05:41:18
【问题描述】:

下面的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]
}

【问题讨论】:

  • 为什么不只使用一个.grep(而不是循环其中几个),而是检查$.inArray(e.id, currentUser.favorites) !== -1?您需要将结果数组按currentUser.favorites order 重新排序吗?
  • 这是一个非常好的问题。答案是我从未听说过 $.inArray。这将使事情变得更快!为每个产品使用 .grep 需要花费大量时间! (我会进入那个)
  • @raina77ow .inArray 只提供位置。它是否一次处理多个位置? (放入整个数组并获取所有位置)。如果不是,则意味着我需要.inArray 每个产品+ 获取具有给定位置的数据。 .grep 似乎是一个更好的解决方案!

标签: javascript jquery loops jshint


【解决方案1】:

把函数放在循环之外:

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

【讨论】:

  • 工作就像一个魅力。 (顺便说一句,我看到你编辑了你的答案!两者都在工作,而且电流非常整洁)
猜你喜欢
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-17
  • 1970-01-01
  • 1970-01-01
  • 2011-10-15
相关资源
最近更新 更多