代码之家  ›  专栏  ›  技术社区  ›  Lloyd Banks

JavaScript-无法更新嵌套For循环[closed]中的数组对象属性

  •  -2
  • Lloyd Banks  · 技术社区  · 7 年前

    我有以下嵌套循环:

    for(var i = 0; i < availabilities.length; i++){
        if(availabilities[i].round === 1){
            //  Return the indices of all objects which share the same event_team_user_id property
            var indices = helperService.findArrayIndices(availabilities, 'event_team_user_id', availabilities[i].event_team_user_id);
            for(var x = 1; x < indices.length; x++){
                availabilities[x].status = availabilities[i].status;
                console.log(availabilities[x]);
            }
        }
    }
    console.log(availabiities);
    

    事件\团队\用户\ id 财产。

    console.log(availabilities[x]); 嵌套在两个循环中可以正确输出数组对象,但是 console.log(availabiities); 返回一个数组对象,其中for循环中所做的更改 属性没有反映出来。

    为什么数组对象中更新的属性没有保存?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Steven B.    7 年前

    如果我们假设 availabiities 因为你已经提到了打印出来的东西,所以它似乎是你的第二个问题 for 循环可能有一些问题。你没有使用 indices 从你家回来 helperService . 你应该这样做 indices[x] 访问的正确索引 availabilities x 应该从0开始。

    let availabilities = [
      {
        round: 1,
        event_team_user_id: 1,
        status: 'shouldmatch'
      },
      {
        round: 2,
        event_team_user_id: 2,
        status: 'shouldnotchange'
      },
      {
        round: 3,
        event_team_user_id: 1,
        status: 'shouldchange',
      },
      {
        round: 4,
        event_team_user_id: 3,
        status: 'shouldnotchange',
      },
      {
        round: 5,
        event_team_user_id: 1,
        status: 'shouldchange'
      }
    ];
    
    
    for(var i = 0; i < availabilities.length; i++){
        if(availabilities[i].round === 1){
            //  Return the indices of all objects which share the same event_team_user_id property
            var indices = [2, 4];
            for(var x = 0; x < indices.length; x++){
                const curr = indices[x];
                availabilities[curr].status = availabilities[i].status;
            }
        }
    }
    console.log(availabilities);
        2
  •  0
  •   deerawan    7 年前

    看来你打字打错了

    之前

    console.log(availabiities);
    

    之后

    console.log(availabilities);