【问题标题】:break; not ending for loop休息;没有结束 for 循环
【发布时间】:2016-02-28 19:37:51
【问题描述】:

所以我有一些我正在尝试解析的 JSON 数据。 'id: 2' 是 'like-count' 的等效操作 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,count:-1”。我也尝试过使用 '.some'(返回 false)和 '.every'(返回 true)来突破,但这也没有用。

'post.actions_summary' 的正确值应该是 {id: 2, count: 10}。

【问题讨论】:

  • 使用console.log(JSON.stringify(action)); 来查看每次迭代在做什么
  • 当我把你的代码放在'action ='下面,在if循环之前,web控制台返回的是:{"id":5,"count":2} | 1 | post.actions_summary | [对象计数:-1id:2__proto__:对象]
  • 我实际上认为我可能知道...在第一个 ELSE 语句之后,'.length' 本质上为 0,这样循环在第一次迭代时终止。我可能应该尝试为 .length 设置一个变量以保留实际值。现在测试。现在我收到一个错误 (Uncaught TypeError: Cannot read property 'id' of undefined(...)) ,当放置时,'i

标签: javascript arrays loops break


【解决方案1】:

使用数组filter方法

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

 post.actions_summary = filtered_actions;

【讨论】:

  • 已添加,如果 (typeof filtered_actions[0] == "undefined") { post.actions_summary.push({id: 2, count: 0}) } 如果未找到则提供默认值.谢谢!
【解决方案2】:

如果我理解得很好,您有一个元素数组,并且您想要获取第一个 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});
}

【讨论】:

    【解决方案3】:

    回答:

    最后,我使用的代码是:

    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}];
      }
    
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      • 2014-02-01
      相关资源
      最近更新 更多