首页 > 解决方案 > 为什么 If 语句在此循环中被视为函数?

问题描述

我一直在构建一个经常使用迭代的 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,它将打破循环,这就是我所做的。我返回一个在循环外声明的变量为真。这让我脱离了循环,并允许我在下面做逻辑。

我还应该指出,这也完全在一个循环中,因为我们正在迭代当前的搜索用户。我没有运行时或编译错误,这段代码运行良好,但也许我正在为将来的灾难做好准备。

任何想法为什么我会收到此错误?如果我错过了一些最佳实践?

标签: javascriptreactjsjslint

解决方案


由于在您引用的第一行中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);

推荐阅读