Return 来自 for 循环中函数回调的值

Return value from a function callback in a for loop

我有以下 for 循环:

import { createSelector } from 'reselect';

let dirtyForm;

export const isFormDirty = createSelector(
    getForms,
    getState,
    (forms, state) => {
        for(let i = 0; i < forms.length; i += 1){
            dirtyForm = isDirty(forms[i])(state);
        }

        return dirtyForm;
    }
);

isDirty from 从表单数组中获取单个表单名称并检查表单是否已被编辑。我循环浏览表单名称的原因是为了查明屏幕上可用的表单是否已被编辑。

它可以工作,但是在这种情况下有没有办法完全不必使用 for 循环?

最后一个表单的状态将始终覆盖循环中的其他状态。

如果您要检测 任何 表格是否有问题,您可以使用 Array.prototype.some():

export const isFormDirty = createSelector(
    getForms,
    getState,
    (forms, state) => forms.some(form => isDirty(form)(state)) // Will return true if one of the forms are dirty, false if all forms are clean
);

或者,正如@Danmoreng 在评论中建议的那样,您可以保留循环,并通过将 dirtyForm 标志与自身添加或运算来防止覆盖:

for (let i = 0; i < forms.length; i += 1) {

    // Once true, further results will not be evaluated, so no overrides
    dirtyForm = dirtyForm || isDirty(forms[i])(state);
}

或者,正如@Icepickle 在评论中所建议的那样,您可以在遇到脏表格时简单地打破循环:

for (let i = 0; i < forms.length; i += 1) {

    // Exit the loop by returning true if a form is dirty
    // Might be wise to add a "return false;" outside the loop with this approach.
    if(isDirty(forms[i])(state)) {
        return true;
    }
}

export const isFormDirty = createSelector(
    getForms,
    getState,
    (forms, state) => forms.some(form => isDirty(form)(state))
);

编辑:根据评论中的优秀建议删除了地图

使用Array.some()检测数组是否有真值条件值。提早退出,非常干净和性能。