JSHint error : Functions declared within loops referencing an outer scoped variable may lead to confusing semantics

末鹿安然 提交于 2020-06-01 06:45:46

问题


Is it possible to explain why this code snippet throws such an error ECMA 6 is not an option as of now and I have also tried putting the inner $.each function in a closure IIFE that saves maps the value of i to an inner variable within the closure. Please help !

for(var i = 0; i < cityArray.length; i++) {
    $.each(_cityCards, function(index, item) {
        var cityName = $(this).attr('data-city');
        if(cityName == cityArray[i]) {
            $(this).css('transform','scale(1)').delay(500).show();
        }
    });
}

回答1:


Sound like JSHint doesn't like how the anonymous function in there is being re-created over and over.

What if you tried pulling out the anonymous function and giving it a name.

Then referencing this named function back in the loop body?

I.e. like

function func (index, item) {
  var cityName = $(this).attr('data-city');
  if(cityName == cityArray[i]) {
    $(this).css('transform','scale(1)').delay(500).show();
  }
}

for(var i = 0; i < cityArray.length; i++) {
    $.each(_cityCards, func);
}


来源:https://stackoverflow.com/questions/46538640/jshint-error-functions-declared-within-loops-referencing-an-outer-scoped-varia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!