为什么在循环中将If语句视为函数?

时间:2018-10-19 16:30:42

标签: javascript reactjs jslint

我一直在构建一个使用迭代的React应用程序。我正在使用JSLint并收到令人讨厌的警告:

  

不要在循环中创建函数

在以下循环中:

if(currentSearch[i].users.length > 0) {
    var matched = false;

    //I hate how JSLint just can't handle setting a variable to true within a function
    //this is loop where I get the warning 
    currentSearch[i].users.some(childUser => {
        if(childUser.id === user.id) {
            return matched = true;
        }
    })
    //^^^^^ Warning

    if(!matched) {
        var alert = new AlertObject(user,currentSearch[i],true,false);
        alerts.push(alert);
    }
}

我不认为我在循环中设置了一个函数?我正在使用array.some函数,如果我返回true,它将中断循环,这是我要做的。我返回在循环外声明的变量为true。这使我脱离了循环,并允许我在下面做逻辑。

我还应该指出,由于我们正在迭代当前的搜索用户,因此这也完全是一个循环。我没有运行时错误或编译错误,并且此代码可以正常工作,但也许将来我会为灾难做准备。

有什么主意为什么会出现此错误?如果我错过了一些最佳做法?

5 个答案:

答案 0 :(得分:2)

由于在第一行中您引用了currentSearch[i],因为[i]我假设您粘贴在此处的整个代码块都处于某种循环内,可能是for。 >

然后,您正在为Array.some回调创建一个函数,该函数会触发错误。

一种解决方案是将回调声明移到父循环之外,但是由于您使用的是作用域中的变量,因此需要进行一些重构。


可能的解决方案

您可以在父循环之外(您在此处提供的代码之外的那个地方)声明一个用于检查子用户的函数。

//Please provide a better name for the function according to the context.
const checkChildUser = function (childUser) {
    return this.id === childUser.id;
};

然后将其传递给您正在使用的Array.some函数:

currentSearch[i].users.some(checkChildUser, user);

答案 1 :(得分:1)

我对React并不熟悉,但这看起来像一个ES6箭头功能:

childUser => { ... }

相当于...

function (childUser) { ... }

答案 2 :(得分:0)

好吧,您正在.some()中提供一个函数作为参数,以便触发警告的原因。

ESLint警告的原因

Writing functions within loops tends to result in errors due to the way the function creates a closure around the loop-source

您可以这样做

function compareId(childUser) {
  if (childUser.id === user.id) {
    return true;
  }
}

if (currentSearch[i].users.length > 0) {
  var matched = currentSearch[i].users.some(compareId);

  if (!matched) {
    var alert = new AlertObject(user, currentSearch[i], true, false);
    alerts.push(alert);
  }
}

答案 3 :(得分:0)

在您的代码段中,Don't make functions within a loop警告不是由if statement引起的,而是由以下匿名函数引起的:

childUser => {
 if(childUser.id === user.id) {
  return matched = true;
 }
}

由于您已经说过整个代码都在循环内,因此每次迭代都会为该匿名函数创建一个新实例。这会影响性能。

答案 4 :(得分:0)

这里的问题是您创建了一个修改matched变量的函数。该变量用var声明,因此它的作用域是整个函数,而不是单个循环迭代。这可能会导致令人惊讶的结果,因为在每次迭代中创建的函数实际上将引用 same 变量。

仅使用some()返回的值而不是在回调中更改matched(如Yury Tarabanko的建议)应删除警告。

相关问题