基于两个条件退出While循环

Exit a While loop based on two conditions

本文关键字:While 循环 退出 条件 于两个      更新时间:2023-09-26

我有一个问题与解析CSV数据的后Javascript代码的答案有关

我发现我在末尾得到了一个额外的"'r'n",我不想将其添加到数组中。我试着打破while循环。。。

原工作线为

 while (arrMatches = objPattern.exec( strData )){

但如果arrMatches = "'r'n"

while ((arrMatches[ 1 ] != "''r''n") && arrMatches = objPattern.exec( strData )){

但是得到CCD_ 3错误。

正确的语法是什么?

只需将这两个条件分开,即可使更具可读性和可理解性

while(arrMatches = objPattern.exec( strData )){
    if(arrMatches[ 1 ] == "'r'n"){
        break;
    }
    /*
     *if(arrMatches[ 1 ] == "'r'n")
     *   break;
     */
     // rest of code
}

这种方法应该有效,唯一的问题是arrMatches也应该在( )之间,以避免arrMatches从第二个条件设置为true。

while ((arrMatches = objPattern.exec( strData )) && (arrMatches[ 1 ] != "''r''n")) {

另一种方法:while运算符的表达式块可以很容易地拆分为逗号分隔的表达式链,期望在最后一个表达式求值为0/false时循环中断。

它不等同于逻辑&链接,因为JS中的逗号','运算符总是返回最后一个表达式。(感谢GitaarLab提醒我

在这些示例中,一旦最后一个变量达到0,循环就会停止,因此计算结果为false。

var i = 10, j = 10;
while (i--, j--) console.log(i);
/*9
8
7
6
5
4
3
2
1
0*/
var i = 10, j = 5;
while (i--, j--) console.log(i);
/*9
8
7
6
5*/
var i = 10, j = 5, k = 3;
while (i--, j--, k--) console.log(i);
/*9
8
7*/

您可以尝试一个处理一个条件的while循环,在while循环中,您有一个检查其他条件的if语句。

示例:

while (one condition) {
   if (other condition) {
       do something;
   }
}

我不完全确定这样做是否合适。如果我找到更好的答案,我会更新我的答案。

尝试:while((arrMatches[1]!="''r''n")&arrMatches==objPattern.exec(strData)){

使用单个"=",实际上是在为arrMatches赋值。为了比较值,您应该使用==

collection = [];
// while loop will run over and over again
while (true) { 
  //declare a variable which will store user input
  var conditionToo = prompt('What is the condition of the weather?');
  if (conditionToo == 'yes') { 
    // if the variable conditionToo contains the string 'yes'
    do something; //append values to the collection
  }
  if else(conditionToo == 'no') {
    // if the variable conditionToo contains string 'no'
    alert('Goodbye cool human :-)');
    break;
   }
}