在循环内在循环上引用外部作用域变量

时间:2019-03-02 22:14:21

标签: javascript jquery

下面的代码出现JSHint / JSLint错误。

Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. ($, currentVal)

这是针对我要推送到$options.each的{​​{1}}循环。

关于如何解决此问题的任何想法?

currentVal

https://codepen.io/anon/pen/drMRem?editors=1111

1 个答案:

答案 0 :(得分:-1)

我使用codepen.io JS Analyze运行,结果是:不要在循环中创建函数。,并带有指向此JS Hint - don't make functions within a loop的链接。您应该将函数移出而不是将其放置在循环中,但是如果您仍然坚持在循环中包含一个函数,则可以像下面那样缩小currentVal范围:

$options.each(function($currentVal) {
  return function() {
    if ($(this).prop("checked") == true) {
      $currentVal.push($(this).attr("id"));
    };
  }(currentVal));

相关问题