【问题标题】:JS Lint Error : Don't make functions within a loop - No workaround [duplicate]JS Lint 错误:不要在循环中创建函数 - 没有解决方法 [重复]
【发布时间】:2016-09-28 22:03:36
【问题描述】:

我在 react JS 中有一个小代码 sn-p,其中我试图在对象“类别”中搜索一个值,然后将相应的键值对插入到新映射 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 错误,我没有得到任何解决方法。

不要在循环中创建函数

【问题讨论】:

标签: javascript node.js reactjs jslint


【解决方案1】:

我看不出有任何理由像这样重构您的代码行不通。基本上我们将回调函数从循环中取出,并使用闭包中的j 变量。我已将 var j 声明移到回调上方以使其看起来不错,但从技术上讲,您不必这样做。

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

【讨论】:

  • 嘿,谢谢!这行得通。但是,如果我想在 forEachMap 找到值并在地图中设置后突破它怎么办。我们该怎么做?
  • 要“突破”forEach,请改用some
【解决方案2】:

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

【讨论】:

  • FWIW,这将保留它试图警告的与性能相关的问题。
猜你喜欢
  • 1970-01-01
  • 2017-08-29
  • 2012-10-05
  • 2011-10-15
  • 2014-08-17
  • 2023-03-30
  • 2012-10-16
  • 2014-03-02
  • 2011-03-03
相关资源
最近更新 更多