[英]I have a no-loop-func issue that I don't know how or if I should bother solving
目前,这并没有破坏我的代码中的任何内容,但我一直看到这是一个通常会导致严重问题的错误,但我不知道到底发生了什么或如何消除错误 go。 如果有人有任何建议,那就太好了。
错误: Function declared in a loop contains unsafe references to variable(s) 'i' no-loop-func
相关代码段:
let i = 0;
let interval = moment()
.day(days[0] + frequency * i)
.toDate();
while (moment(endDate).isAfter(interval)) {
days.map((day) =>
selectedDays.push(
moment()
.day(day + frequency * i)
.toDate()
)
);
interval = moment()
.day(days[0] + frequency * ++i)
.toDate();
}
遵循警告:
在循环中声明的 Function 包含对变量“i”的不安全引用
由于您的 while 循环只有一个 function 声明(每次迭代),我们可以假设以下代码是问题所在:
(day) => selectedDays.push( moment().day(day + frequency * i).toDate() )
箭头 function中对i
的引用会触发警告,因为 JavaScript 短绒不知道何时/何地调用声明的函数。
查看no-loop-func
规则示例时:
for (let i=10; i; i--) { var a = function() { return i; }; // OK, all references are referring to block scoped variables in the loop. a(); }
您可以看到可以通过使用块作用域变量来解决此警告。 当应用于您当前的代码时,它可能如下所示:
while (moment(endDate).isAfter(interval)) {
// store the value used by the function in a block-scoped constant
const period = frequency * i;
days.map((day) =>
selectedDays.push(
moment()
.day(day + period)
.toDate()
)
);
// ...
}
如果您不打算使用返回值,您还应该避免使用map()
。 对于迭代使用forEach()
或for...of
循环。
另一种选择是根本不声明 function,这可以通过使用for...of
来完成。
while (moment(endDate).isAfter(interval)) {
for (const day of days) {
selectedDays.push(
moment()
.day(day + frequency * i)
.toDate()
);
}
// ...
}
以上完全删除了 function 声明。
发生这种情况是因为您在 while 循环之外声明interval
,然后在 while 循环内对其进行修改。 这可能导致意外行为。 您可以在顶部的 while 循环中声明interval
,它可能会解决您看到的错误/警告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.