我对此帖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
错误。
正确的语法是什么?
谢谢
答案 0 :(得分:7)
将这两个条件分开以使其更具可读性和可理解性
while(arrMatches = objPattern.exec( strData )){
if(arrMatches[ 1 ] == "\r\n"){
break;
}
/*
*if(arrMatches[ 1 ] == "\r\n")
* break;
*/
// rest of code
}
答案 1 :(得分:4)
这种方法应该有效,唯一的问题是arrMatches也应该在( )
之间,以避免arrMatches
从第二个条件设置为true。
while ((arrMatches = objPattern.exec( strData )) && (arrMatches[ 1 ] != "\\r\\n")) {
答案 2 :(得分:2)
另一种方式: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*/
答案 3 :(得分:1)
您可以尝试处理一个条件的while
循环,并且在while
循环内,您有一个if
语句来检查其他条件。
示例:
while (one condition) {
if (other condition) {
do something;
}
}
这是否是适当的方式,我不完全确定。如果我找到更好的东西,我会更新我的答案。
答案 4 :(得分:0)
尝试: while((arrMatches [1]!=“\ r \ n”)&& arrMatches == objPattern.exec(strData)){
使用单个'=',您实际上是为 arrMatches 分配值。为了比较值,您应该使用 == 。
答案 5 :(得分:0)
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;
}
}