I need to know my JavaScript sentence is correct or not? I am very much confused with the single quotes and plus symbols.
document.f.SQL.value ='\('+
document.f.SQL.value + a[i] +
' >= \''+ document.f[a[i]+"_A"].value +
'\' AND '+ a[i] +' <= \''+
document.f[a[i]+"_B"].value +
'\) or DATEADD'+'\('+
'dd, 0, DATEDIFF'+'\('+
'dd, 0,'+ a[i] +'\)) = \''+
document.f[a[i]].value +
'\'';
I pasted your code in Closure Compiler and used the which gave no errors, so the syntax is correct. The generated code is:
document.f.SQL.value = "(" + document.f.SQL.value + a[i] + " >= '" + document.f[a[i] + "_A"].value + "' AND " + a[i] + " <= '" + document.f[a[i] + "_B"].value + ") or DATEADD" + "(" + "dd, 0, DATEDIFF" + "(" + "dd, 0," + a[i] + ")) = '" + document.f[a[i]].value + "'";
The options I used for this:
- Optimization: Whitespace only
- Formatting: Pretty print
Try to avoid such complex lines. Make use of variables. The same result could be achieved with the below:
var old = document.f.SQL.value + a[i];
var sql_a = document.f[ a[i] + "_A" ].value;
var sql_b = document.f[ a[i] + "_B" ].value;
var whatever = document.f[ a[i] ].value;
// (old) >= 'sql_a' AND
var sql = "(" + old + ") >= '" + sql_a + "' AND ";
// A <= 'sql_b')
sql += a[i] + " <= '" + sql_b + "') "
// or DATEADD(dd, 0, DATEDIFF(dd, 0, A)) = 'whatever'
sql += "or DATEADD(dd, 0, DATEDIFF(dd, 0, " + a[i] + ")) = '" + whatever + "';
document.f.SQL.value = sql;
The point is, try to split the string in smaller parts. I did not split the queries in smaller parts above, that's up to you.
If you need single quotes in your string and no double quotes (inside it) then use double quotes to delimit your string and you won't need to escape your single quotes.
I usually prefer single quotes to delimit strings in JavaScript especially when I tend to be working on HTML strings because I prefer double quotes for attributes. You can use either the single quote or double quote though, there's no functional difference like there is in PHP or other languages.
Your expression is quite difficult to read. Consider simplifying it, putting it into several instructions or finding/writing a reusable token substitution routine of some sort.
The escaping of brackets \(
looks unnecessary, and concatenating two string literals too ' + '
.
Expressions like document.f[a[i]+"_A"].value
would be easier to read if they were assigned to meaningfully named variables before you used them.
精彩评论