I have for loop which goes through the array with arguments. When next argument is "?", "&" or "||", it shouldn't add comma, however, it always adds. I couldn't understand why, here is the code:
var args = ["arg1","arg2","?","arg3"];
var query = "";
for (var i = 0; i < args.length; i++) {
switch (args[i]) {
case "?":
query += " where ";
break;
case "&":
query += " and ";
break;
case "||":
query += " or ";
break;
default:
if (args[i+1] != "?");
{
query += args[i] + ", ";
break;
}
query += args[i] + " ";
break;
}
}
document.write(query);
When I type this (this is splitted by " " and sent to array args):
arg1 arg2 ? arg3
It prints it like this:
arg1, arg2, where arg3, // while it should be arg1, arg2 where arg3,
Thanks for helping people, problem was caused by an extern script. And yes, I removed semicolon ;)
4 Answers 4
Your if statement is broken:
if (args[i+1] != "?"); // <---- remove that semicolon
{
query += args[i] + ", ";
break;
}
You've got a stray semicolon. It is not a syntax error, but it means the if doesn't do anything. The code that adds the comma always runs, and exits the switch before the code that doesn't add the comma.
10 Comments
You have a semicolon between your if and your block:
if (args[i+1] != "?");
Should be
if (args[i+1] != "?")
Comments
There may be completely different ways to solve this problem which would make your code easier to extend without deepening trees of if or switch
A quick example,
// define some dictionaries
let logicDict = Object.assign(Object.create(null), {
'?': 'where',
'&': 'and',
'||': 'or'
});
// define some flags
let noComma = false;
// reduce your array
['arg1', 'arg2', '?', 'arg3'].reduceRight((str, e) => {
if (e in logicDict) {
noComma = true;
return logicDict[e] + ' ' + str;
}
if (!noComma) e += ',';
noComma = false;
return e + ' ' + str;
}, '').slice(0, -1);
// "arg1, arg2 where arg3,"
1 Comment
Thanks for noticing semicolon guys, problem was caused by an extern script.
3 Comments
query and to hook args up to process.argv as a Node.js program, did not work with the semicolon but it did work correctly once the semicolon was removed.
arg1, arg2, where arg3, // while it should be arg1, arg2 where arg3,?arg2beforewhereis not wanted apparently.toStringmethod adds the comma.if (args[i+1] != "?");oops!