首页 > 解决方案 > javascript code raising warning in jshint.com "Functions declared within loops referencing an outer scoped variable may lead to confusing semantics"

问题描述

The javascript code:

for (j = 0; j < array.length; j ++) {
    if (
        array[j].some(
            function(word) {
                return word.indexOf(array1[i]) > -1;
            }
        )
    ) {
        makeSomething();
    }
}

produces a Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (array1) warning in jshint.com.

Actually it works.

Is it really problematic?

How should it be written?

标签: javascript

解决方案


不,这不是问题。警告缺少推理:

如果回调将被异步回调,那么它会令人困惑:

   for(i = 0; i < 10; i++) {
      setTimeout(function() {
        console.log(i); // guess what this logs
      });
  }

但是你真的应该总是声明变量总是使用letor const

  for (let j = 0; j < array.length; j ++) {

这将使警告消失,并且还将修复上面的示例(并且它避免了可能令人困惑的隐式 global)。


推荐阅读