【问题标题】:Loop through an array of objects and check it's properties循环遍历对象数组并检查其属性
【发布时间】:2017-10-27 20:32:26
【问题描述】:

我有一个分配给 in_timings 变量的对象数组。我想检查对象的某些条件,以便为某些执行做准备。 我不知道我做错了什么,但循环似乎在我没想到的块上执行。

in_timings:TimeInModel[];
    ...........
fetchTimeIns(){
this.employeesService.getTimeIn()
.subscribe(result=>this.in_timings = result,
error => this.errorMessage = <any>error);
 }
  .......................
  ...............

      for(let in_timing of this.in_timings)
  {
      if(in_timing.employee_id===emp_id && in_timing.is_active===true){   

      console.log("You have already checked in!");

    }
     else if((in_timing.employee_id===emp_id && in_timing.is_active===false) || this.in_timings.length<0){

       console.log("Add another row here...");

     }
    else{
      console.log("All conditions exhausted!");
    }
  }

在图像中,它显示了第一个语句被执行了,最后一个语句被执行了两次。

我已经记录了对象数组以显示结构。

【问题讨论】:

  • 您希望发生什么?
  • 我期望的是,只有一个块可以执行。我想要的是,被指示如何做到这一点。
  • one block to execute是什么意思?
  • 你想要发生的行为是什么。如果当前用户在列表中有活动时间,则什么也不做。如果它没有计时,或者有一个不活跃的计时,那么做其他事情吗?

标签: html angular typescript ionic2


【解决方案1】:

据我了解,如果任何一个条件为真,您希望 break 执行您的问题。这样做会使你的代码只运行一个块。

只需在日志后添加break关键字即可。

  for(let in_timing of this.in_timings)
  {
  if(in_timing.employee_id===emp_id && in_timing.is_active===true){   

  console.log("You have already checked in!");
   break;

}
 else if((in_timing.employee_id===emp_id && in_timing.is_active===false) || this.in_timings.length<0){

   console.log("Add another row here...");
   break;

 }
else{
  console.log("All conditions exhausted!");
   break;
}

【讨论】:

    猜你喜欢
    • 2016-03-11
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 2021-11-20
    相关资源
    最近更新 更多