[英]Loop check if on last iteration?
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 "
}
}
}
Your i
is always smaller than QuerySplit.length
- that's your loop condition. 你的
i
总是比QuerySplit.length
小 - 这就是你的循环条件。 In the last iteration it will have a value of QuerySplit.length-1
, that's what you can check against: 在最后一次迭代中,它将具有
QuerySplit.length-1
的值,这是您可以检查的内容:
if (i < QuerySplit.length - 1)
Btw, you'd do better to use the join
Array method for what you're trying to do: 顺便说一句,你最好使用
join
Array方法来做你想做的事情:
var NewQuery = QuerySplit.map(function(x){return x.value;}).join(" AND ");
Take note that you need var NewQuery = "";
请注意,您需要
var NewQuery = "";
and check for length - 1. Also, the last if statement is just a guess of what you probably want to do: 并检查长度 - 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,这是您的最后一次迭代。
The array is 0-based. 该数组是从0开始的。 This means if there are 3 items in the array, your indexes will be
0,1,2
. 这意味着如果数组中有3个项目,则索引将为
0,1,2
。 The last one is one less than the length. 最后一个比长度少一个。
You'll have to check like this: (i < QuerySplit.length -1)
你必须这样检查:
(i < QuerySplit.length -1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.