Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Loops 对于带中断或条件循环的循环,哪一种做法更好?_Loops_For Loop_While Loop_Language Agnostic - Fatal编程技术网

Loops 对于带中断或条件循环的循环,哪一种做法更好?

Loops 对于带中断或条件循环的循环,哪一种做法更好?,loops,for-loop,while-loop,language-agnostic,Loops,For Loop,While Loop,Language Agnostic,我只是好奇人们对这个话题的看法。假设我有一个对象数组,我想循环它们,看看对象是否包含某些值,如果是,我想停止循环。哪一种做法更好?带中断的for循环,还是条件循环 我提供的示例中的伪代码仅用于参数(它也在ActionScript中,因为这是我最近的主要语言)。另外,我也不是在寻找关于语法的最佳实践想法 对于带中断的循环: var i:int; var isBaxterInMilwaukee:Boolean; for (i = 0; i < arrayLen; i++) {

我只是好奇人们对这个话题的看法。假设我有一个对象数组,我想循环它们,看看对象是否包含某些值,如果是,我想停止循环。哪一种做法更好?带中断的for循环,还是条件循环

我提供的示例中的伪代码仅用于参数(它也在ActionScript中,因为这是我最近的主要语言)。另外,我也不是在寻找关于语法的最佳实践想法

对于带中断的循环:

var i:int;

var isBaxterInMilwaukee:Boolean;    

for (i = 0; i < arrayLen; i++)
{
    if (myArray[i]["name"] == "baxter"
         && myArray[i]["location"] == "milwaukee")
    {
        isBaxterInMilwaukee = true;

        barkTwice();

        break;
    }
}
vari:int;
var isBaxterInMilwaukee:布尔值;
对于(i=0;i
条件循环:

var i:int;

var isBaxterInMilwaukee:Boolean;    

while (!isBaxterInMilwaukee && i < arrayLen)
{
    if (myArray[i]["name"] == "baxter"
         && myArray[i]["location"] == "milwaukee")
    {
        isBaxterInMilwaukee = true;

        barkTwice();
    }

    i++;
}
vari:int;
var isBaxterInMilwaukee:布尔值;
而(!isBaxterInMilwaukee&&i
我认为这要视情况而定。在这种情况下,带中断的循环对我来说似乎更清晰。

我一直不喜欢在代码中使用
中断
。。。在这种情况下,这似乎无关紧要,但在更复杂的循环中,它可能会让另一个阅读它的程序员感到非常困惑。一般来说,在编码者发现嵌套的
中断
深入循环之前,它常常导致不理解循环如何终止。通过指定每次循环迭代都要检查的标志条件,它使这一点更加清晰

这个问题类似于
return
语句深入方法体,不容易发现(而不是设置
retVal
变量并在方法末尾返回)。用一个小的方法,这看起来很好,但它越大,就越令人困惑

这不是操作效率的问题,而是可维护性的问题


询问你的同事在特定情况下什么是可读和可理解的。。。这才是真正重要的。

最有意义的是将想法传达给阅读代码最好的人。首先记住代码的可读性,您通常会做出正确的选择。通常,除非您真的需要,否则您不想使用类似于
break
的东西,因为如果经常使用,甚至只是在一组嵌套很深的表达式中使用,可能会使事情难以理解
continue
有时可以起到与中断相同的作用,然后循环将正常退出,而不是因为它已中断。在这种情况下,我可以用几种不同的方式来写这个

可能您在这里最想要的是修改
while
循环:

while(!isBaxterInMilwaukee || i < arrayLen) {
  if(myArray[i]["name"] == "baxter" && myArray[i]["location"] == "milwaukee") {
    isBaxterInMilwaukee == true;
    barkTwice()
  } else {
    i++;
  }
}
while(!isBaxterInMilwaukee | | i
这一点很清楚,并且不使用
中断
继续
,因此您可以一眼看出,您总是会由于
while
表达式中指定的某个条件而终止


ETA:可能应该在
循环中
i
,否则它会第一次失败,除非输入值与目标值相同…

我会说break,更清晰(即使你在注释中说明为什么要中断循环)
如果while循环不清楚,我会选择break

我在两个循环中都看到了break,对吗

无论如何:

  • 当循环开始之前有已知的迭代次数(最大次数)时,我会选择FOR循环
  • 否则我会选择
  • 在FOR循环中,我使用自由断开
  • 在WHILE循环中,我更喜欢使用复杂条件而不是中断(如果可能的话)

在for循环中,也可以通过在for循环声明中放入早期退出条件来提前退出。因此,对于您的示例,您可以这样做:

var i:int;

var isBaxterInMilwaukee:Boolean;    

isBaxterInMilwaukee = false;

for (i = 0; i < arrayLen && !isBaxterInMilwaukee; i++)
{
    if (myArray[i]["name"] == "baxter"
        && myArray[i]["location"] == "milwaukee")
    {
        isBaxterInMilwaukee = true;

        barkTwice();
    }
}
vari:int;
var isBaxterInMilwaukee:布尔值;
isBaxterInMilwaukee=假;
对于(i=0;i

这样您就不需要中断,而且它比while循环更具可读性。

简而言之,您应该选择最容易阅读和维护的版本。

在稍大一点的时间里,我知道一个循环的突破被认为是一个NO(与Goto语句一致)。循环应该在循环条件下中断,而不是在其他任何地方。因此,while循环应该是一种方式

(这可能是程序集的遗留问题,其中循环基本上是一个代码块,末尾有一个go to the start if true jump语句。块中的多个条件跳转语句使得调试非常困难;因此要避免它们,并在最后合并为一个。)

我觉得这个想法在今天似乎有所改变,特别是在foreach循环和托管世界中;现在真的是风格问题了。为循环找到的中断可能已经被许多人接受,当然,除了一些纯粹主义者。请注意,我仍然会避免在while循环中使用break,因为这会混淆循环条件并使其混淆

如果允许我使用一个FURACH循环,我认为下面的代码比它的while循环兄弟更容易阅读:

bool isBaxterInMilwaukee;    

foreach (var item in myArray)
{
    if (item.name == "baxter" && item.location == "milwaukee")
    {
        isBaxterInMilwaukee = true;    
        barkTwice();
        break;
    }
}
<>但是,随着逻辑在复杂度上的增长,你可能想在Buffy/Cuth>语句旁边考虑一个突出的注释,以免它被埋没,很难找到。
bool isBaxterInMilwaukee(Array myArray)
{      
    foreach (var item in myArray)
    {
        if (item.name == "baxter" && item.location == "milwaukee")
        {
            barkTwice();
            return true;
        }
    }
    return false;
}
var i:int;

var isBaxterInMilwaukee:Boolean;    

for (i = 0; !isBaxterInMilwaukee && i < arrayLen; i++)
{
    if (myArray[i]["name"] == "baxter"
         && myArray[i]["location"] == "milwaukee")
    {
        isBaxterInMilwaukee = true;    
        barkTwice();
    }
}
var i:int = -1;

var isBaxterInMilwaukee:Boolean;    

while (!isBaxterInMilwaukee && ++i < arrayLen)
{
    if (myArray[i]["name"] == "baxter"
         && myArray[i]["location"] == "milwaukee")
    {
        isBaxterInMilwaukee = true;
        barkTwice();
    }
}
while (counter <= end) {
   // do really cool stuff
   ++counter;
}
for (int tryCount=0; tryCount<2; ++tryCount) {
    if (someOperation() == SUCCESS) {
       break;
    }
}
// what we are looking for?
IsPersonInLocation condition = new IsPersonInLocation("baxter", "milwaukee");

// does the array contain what we are looking for?
bool found = myArray.Find(item => condition.IsSatifiedBy(item));

// do something if the condition is satisfied
if (found) {
    barkTwice();
}
class IsPersonInLocation {
    public string Person { get; set; }
    public string Location { get; set; }
    public IsPersonInLocation(string person, string location) {
        this.Person = person;
        this.Location = location;
    }
    bool IsSatifiedBy(item) {
        return item["name"] == this.Person
            && item["location"] == this.Location;
    }
}
if(myArray.some(function(o) { o.name == "baxter" && o.location == "milwaukee" }))
  barkTwice();
if(myArray.containsMatch({name:"baxter",location:"milwaukee"})
  barkTwice();
class Program
{
   static bool IsBaxterInMilwaukee(IList<WhoAndWhere> peopleAndPlaces)
   {
      foreach (WhoAndWhere personAndPlace in peopleAndPlaces)
      {
         if (personAndPlace.Name == "Baxter" 
            && personAndPlace.Location == "Milwaukee")
         {
            return true;
         }
      }
      return false;
   }

   static void Main(string[] args)
   {
      List<WhoAndWhere> somePeopleAndPlaces = new List<WhoAndWhere>();
      somePeopleAndPlaces.Add(new WhoAndWhere("Fred", "Vancouver"));
      somePeopleAndPlaces.Add(new WhoAndWhere("Baxter", "Milwaukee"));
      somePeopleAndPlaces.Add(new WhoAndWhere("George", "London"));

      if (IsBaxterInMilwaukee(somePeopleAndPlaces))
      {
         // BarkTwice()
         Console.WriteLine("Bark twice");
      }
   }

   public class WhoAndWhere
   {
      public WhoAndWhere(string name, string location)
      {
         this.Name = name;
         this.Location = location;
      }

      public string Name { get; private set; }
      public string Location { get; private set; }
   }

}
let barkTwice = () => {
    console.log('bark twice');
}

let arr = [{
        location: "waukee",
        name: "ter"
    }, {
        location: "milwaukee",
        name: "baxter"
    },
    {
        location: "sample",
        name: "sampename"
    }
];
arr.find(item => {
    if (item.location == "milwaukee" && item.name == "baxter") {
        barkTwice();
        return true
    }
});