破;不结束循环

break; not ending for loop

本文关键字:循环 结束      更新时间:2023-09-26

所以我有一些JSON数据正在尝试解析。"id: 2"是"赞计数"的等效操作 ID。出于测试目的,我将"post.actions_summary"数组设置为,

post.actions_summary.push({id: 5, count: 2}, {id: 6, count: 2}, {id: 2, count: 10}, {id: 10, count: 10});

应该通过这个数组解析的代码如下:

for (i = 0; i < post.actions_summary.length; i++ ) {
  action = post.actions_summary[i];
  if (action.id === 2) {
    aID = action.id;
    aCOUNT = action.count;
    post.actions_summary = [];
    post.actions_summary.push({id: aID, count: aCOUNT});
    break;
  } else {
    post.actions_summary = [];
    post.actions_summary.push({id: 2, count: -1});
  }
}

但是,在检查"post.actions_summary"的值时,我不断得到一个带有一个元素的数组,该元素具有"id:2,计数:-1"。我也尝试使用".some"(返回假)和".every"(返回真)来突破,但这也没有奏效。

"post.actions_summary"的正确值应为 {id: 2, count: 10}。

使用数组过滤器方法

filtered_actions = post.actions_summary.filter(function(action){
        return action.id == 2
    });
 post.actions_summary = filtered_actions;

如果我理解得很好,你有一个元素数组,你想得到第一个 id 等于"2"的元素,如果没有元素的 id 等于"2"你想用默认元素初始化你的数组(值等于"-1")。

如果我是对的,你的算法中有一个错误:如果数组中的第一个元素不等于"2",你用默认元素初始化你的数组,不管你的数组大小如何,你将始终停止在第一个元素。

一个可能的解决方案:

var post = {actions_summary:[]};
post.actions_summary.push({id: 5, count: 2}, {id: 6, count: 2}, {id: 2, count: 10}, {id: 10, count: 10});
var result = []; // bad idea to edit the size of post.actions_summary array during the loop
var found = false
for (var i = 0; i < post.actions_summary.length && !found; i++ ) {
  action = post.actions_summary[i];
  found = action.id === 2;
  if (found) {
    aID = action.id;
    aCOUNT = action.count;
    result.push({id: aID, count: aCOUNT}); 
  }
}
if(!found){
    result.push({id: 2, count: -1});
}

答案:

最后,我使用的代码是:

posts.forEach(function(post) {
  filtered_actions =
  post.actions_summary.filter(function(action){
        return action.id == 2
  });
  if (typeof filtered_actions[0] !== "undefined") {
     post.actions_summary = filtered_actions;
  } else {
     post.actions_summary = [{id: 2, count: 0}];
  }
  });