PDA

View Full Version : saving a conditional value inside a loop


djr
09-22-2010, 03:57 PM
I trying to do something that is very simple in most any language,
but its behavior in javascript is very strange - probably because of my poor understanding of scope, etc.
[CODE]
while (tableA.next()) {

while (tableB.next()) {

var a_field1 = tableA.field1.toLowerCase();
var b_field1 = tableB.field1.toLowerCase();
if (b_field1 == a_field1) {

var a_field2 = tableA.field2.toLowerCase();
var b_field2 = tableB.field2.toLowerCase();
if (b_field2 == a_field2) {
matched_field2 = b_field2;
}
}
}
}
[CODE]

I find a match and matched_field2 is assigned.
The next one matchs on field1 but not field2
but it still re-assigns matched_field2 !!

Lerura
09-23-2010, 09:27 AM
You have told the script to assign if match is found, but you havent told it to un-asssign if no match is found.

Neither are you resetting matched_field2 between the match-checks.while (tableA.next()) {

while (tableB.next()) {
matched_field2 = '';
var a_field1 = tableA.field1.toLowerCase();
var b_field1 = tableB.field1.toLowerCase();
if (b_field1 == a_field1) {

var a_field2 = tableA.field2.toLowerCase();
var b_field2 = tableB.field2.toLowerCase();
if (b_field2 == a_field2) {
matched_field2 = b_field2;
}
else{
matched_field2 = '';
}
}
}
}

You can use either the blue:
assign '' to matched_field2 and it will only be changed if a match is found.

or

the red:
setting matched_field2 to '' if no match is found.
(This requires that the is a match on the field1's to reach this part of the script.)

This might be the solution that you are looking for:
while (tableA.next()) {

while (tableB.next()) {

var a_field1 = tableA.field1.toLowerCase();
var b_field1 = tableB.field1.toLowerCase();
var a_field2 = tableA.field2.toLowerCase();
var b_field2 = tableB.field2.toLowerCase();
if (b_field1 == a_field1 && b_field2 == a_field2) {
matched_field2 = b_field2;
}
else{
matched_field2 = '';
}
}
}

And in the future: this sub-forum is for complete scripts, not for questions!! use the main forum.