Exit the two-condition while loop

I have a question related to the answer to this post Javascript code for parsing CSV data

I find that I get an extra "\ r \ n" at the end that I don't want to add to the array. I tried to break out of the while loop ...

Original working line

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

but I need to break out if arrMatches = "\ r \ n"

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

but get an Invalid left-hand side in assignment error.

What is the correct syntax?

thanks

+4
source share
5 answers

This approach should work, the only thing arrMatches should be between ( ) too is to avoid arrMatches if the second condition is set to true.

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

just separate the two conditions to make them more readable and understandable

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

Another way: while expression block of the while statement can be easily broken into a comma-separated chain of expressions that expect the loop to break when the last expression evaluates to 0 / false.

It is not equivalent to the logical && chain , since the comma operators ',' in JS always return the last expression. (Thanks to GitaarLab for reminding me of this)

In these examples, the loop stops when the last variable reaches 0 and therefore evaluates to 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*/ 
+2
source

You can try a while that processes one condition, and inside the while you have an if that checks another condition.

Example:

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

Whether this is a suitable way to do this, I'm not quite sure. I will update my answer if I find something better.

+1
source

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

With one '=', you are actually assigning an arrMatches value. To compare values ​​you should use == .

0
source

Source: https://habr.com/ru/post/1433916/


All Articles