javascript 循环检查是否在上次迭代中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17304978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:48:48  来源:igfitidea点击:

Loop check if on last iteration?

javascript

提问by Neil

How do I check if I'm on the last iteration of this loop? I'm sorry for asking this question. I'm used to programming in VB.NET and javascript seems very cryptic by nature.

如何检查我是否处于此循环的最后一次迭代?我很抱歉问这个问题。我习惯于在 VB.NET 中编程,而 javascript 本质上似乎非常神秘。

if (QuerySplit.length > 1) {
   var NewQuery
   for (i=0; i<QuerySplit.length; i++)
   {
       // if we're not on the last iteration then
       if (i != QuerySplit.length) {
           // build the new query
           NewQuery = QuerySplit[i].value + " AND "
       }
    }
}

回答by Bergi

Your iis always smallerthan QuerySplit.length- that's your loop condition. In the last iteration it will have a value of QuerySplit.length-1, that's what you can check against:

i永远较小QuerySplit.length-这就是你的循环状态。在最后一次迭代中,它的值为QuerySplit.length-1,这就是您可以检查的值:

if (i < QuerySplit.length - 1)

Btw, you'd do better to use the joinArray methodfor what you're trying to do:

顺便说一句,您最好将joinArray 方法用于您要执行的操作:

var NewQuery = QuerySplit.map(function(x){return x.value;}).join(" AND ");

回答by David Sherret

Take note that you need var NewQuery = "";and check for length - 1. Also, the last if statement is just a guess of what you probably want to do:

请注意,您需要var NewQuery = "";并检查长度 - 1。此外,最后一个 if 语句只是对您可能想要做什么的猜测:

if (QuerySplit.length > 1) {
  var NewQuery = "";
  for (i = 0; i < QuerySplit.length; i++) {
    // if we're not on the last iteration then
    if (i != QuerySplit.length - 1) {
      // build the new query
      NewQuery += QuerySplit[i].value + " AND "
    } else {
      NewQuery += QuerySplit[i].value;
    }
  }
}

If QuerySplit.length is 4, then:

如果 QuerySplit.length 为 4,则:

0, 1, 2, 3

0, 1, 2, 3

...are the indexes. So you want to check for when the index is 3 and that's your last iteration.

...是索引。所以你想检查索引何时为 3,这是你的最后一次迭代。

回答by Dallas

The array is 0-based. This means if there are 3 items in the array, your indexes will be 0,1,2. The last one is one less than the length.

该数组是从 0 开始的。这意味着如果数组中有 3 个项目,您的索引将为0,1,2. 最后一个比长度少一个。

You'll have to check like this: (i < QuerySplit.length -1)

你必须像这样检查: (i < QuerySplit.length -1)