JSHint错误:在循环中声明的引用外部作用域变量的函数可能会导致语义混乱 [英] JSHint error : Functions declared within loops referencing an outer scoped variable may lead to confusing semantics
问题描述
是否有可能解释为什么这段代码片段引发这样的错误?ECMA 6到目前为止还不是一个选项,我还尝试将内部$ .each函数放入闭包IIFE中,该函数保存将i的值映射到闭包内的内部变量。请帮忙!
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();
}
});
}
推荐答案
听起来像JSHint不会就像如何一遍又一遍地重新创建其中的匿名函数。
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?
Ie例如
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);
}
这篇关于JSHint错误:在循环中声明的引用外部作用域变量的函数可能会导致语义混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!