代码之家  ›  专栏  ›  技术社区  ›  Aessandro

for循环中函数回调的返回值

  •  1
  • Aessandro  · 技术社区  · 6 年前

    我有以下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;
        }
    );
    

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

    3 回复  |  直到 6 年前
        1
  •  5
  •   mehmetseckin    6 年前

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

    如果你想知道 任何 其中一张表格很脏,你可以用 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);
    }
    

    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;
        }
    }
    
        2
  •  0
  •   Jolleyboy    6 年前

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

    编辑:删除地图每优秀的意见在评论

        3
  •  0
  •   Justin    6 年前

    使用 Array.some()

    推荐文章