如何使用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);
}