5

我有一个与这篇文章的答案有关的问题Javascript code to parse CSV data

我发现我"\r\n"最后得到了一个我不想添加到数组中的额外内容。我试图打破while循环......

原来的工作线是

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

但我需要打破如果arrMatches = "\r\n"

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

但得到一个Invalid left-hand side in assignment错误。

什么是正确的语法?

4

6 回答 6

7

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

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

    if(arrMatches[ 1 ] == "\r\n"){
        break;
    }
    /*
     *if(arrMatches[ 1 ] == "\r\n")
     *   break;
     */
     // rest of code
}
于 2012-09-13T00:37:42.047 回答
5

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

while ((arrMatches = objPattern.exec( strData )) && (arrMatches[ 1 ] != "\\r\\n")) {
于 2012-09-13T01:00:46.497 回答
3

另一种方式:运算符的表达式块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*/
于 2013-05-30T07:26:06.597 回答
1

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

例子:

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

这是否是适当的方法,我不完全确定。如果我发现更好的东西,我会更新我的答案。

于 2012-09-13T00:38:08.917 回答
0

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

使用单个“=”,您实际上是在为arrMatches分配一个值。为了比较值,您应该使用==

于 2012-09-13T00:23:25.800 回答
-1
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;
   }
}
于 2020-10-14T18:13:53.643 回答