JS林特错误:不要在一个循环内的function – 没有解决方法

我有一个反应JS中的小代码片段,其中我试图search对象“类别”中的值,然后将相应的键值对插入到新的映射sortedCategories

 var categoriesToSort = []; //categoriesToSort has some values var sortedCategories = new Map(); for(var j = 0 ; j < categoriesToSort.length ; j++) { categories.forEachMap(function(key, value){ if(categoriesToSort[j] === value) { sortedCategories.set(key, value); } }); } 

但是这是给我以下lint错误,我没有得到任何解决方法。

不要在循环中创build函数

如何使用forEach而不是for循环?

 var categoriesToSort = []; //categoriesToSort has some values var sortedCategories = new Map(); categoriesToSort.forEach(function (cat) { categories.forEachMap(function(key, value){ if(cat === value) { sortedCategories.set(key, value); } }); }); 

我没有看到任何重构你的代码的原因,这是行不通的。 基本上我们把callback函数放在循环之外,并且像closures中一样使用jvariables。 我已经将var j声明移到了callback之上,使得它看起来不错,但是在技术上你不需要。

 var categoriesToSort = []; //categoriesToSort has some values var sortedCategories = new Map(); var j; var itter = function(key, value) { if(categoriesToSort[j] === value) { sortedCategories.set(key, value); } }; for(j = 0 ; j < categoriesToSort.length ; j++) { categories.forEachMap(itter); }