[英]Conditional statement inside for loop
II have a basic for loop to loop through a data feed: II有一个基本的for循环来遍历数据馈送:
for(var i = 0; i<items.length; i++) {
Then several variables are defined in this form: 然后,以这种形式定义了几个变量:
var x = items.content[i]
Now I want to do something if one of the values of x
equals a value from outside the loop ( y
): 现在,如果
x
的值之一等于循环( y
)之外的值,我想做些事情:
if (x == y) { //do something }
All values of x
and y
will always be unique, so there can never be more than one match - but there may be none. x
和y
所有值将始终是唯一的,因此永远不会有多个匹配项-但可能没有一个。
The problem comes next - I want to do something else if there is no match, if no value of x
matches y
. 接下来是问题-如果没有匹配项,如果
x
值都不匹配y
,我想做其他事情。
If I just do something like: 如果我只是做类似的事情:
else { //do something else }
the else
condition is also satisfied by other values of x
. 在
else
条件也被其他值满足x
。 I have tried putting break;
我曾尝试过
break;
after the if
condition, but unless the match is found on the first value of x
, both conditions are satisfied and both actions are triggered. 在
if
条件之后,但是除非在x
的第一个值上找到匹配项,否则两个条件都将满足并且两个动作都将被触发。 How do I construct this so that the first action is triggered if there is a match between x
and y
, but the second action is triggered only if all values of x
don't match y
? 我该如何构造它,以便在
x
和y
之间存在匹配项时触发第一个动作,但只有在x
所有值都不与y
匹配时才触发第二个动作?
Thanks for any suggestions or advice. 感谢您的任何建议。
Create a boolean that will hold the result of finding 'y', then execute the actions outside of the loop depending on that boolean: 创建一个将保存查找“ y”的结果的布尔值,然后根据该布尔值执行循环外的操作:
var match = false;
for(var i = 0; i<items.length; i++) {
var x = items.content[i]
if(x == y) {
match = true;
// a match is found, there is no need to continue,
break;
}
}
if(match) {
//do something
} else {
//do something else
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.