Forum Moderators: open
Any ideas?
Thanks,
Justin.
THE CODE:
################
data = new Array(
new Array('156', '321', '67', '275'),
new Array('252', '56', '23', '300'),
new Array('400', '290', '321', '312'),
new Array('343', '210', '234', '390'),
new Array('332', '190', '143', '230')
);findRangeMin(data);
function findRangeMin(arr) {
if (typeof arr[0] == 'object') {
var min = arr[0][0];
for (var arrNum in arr) {
for (var i in arr[arrNum]) {
Response.write(arr[arrNum][i] + ' < ' + min +' ?');
if (arr[arrNum][i] < min) { // <== The problem
min = arr[arrNum][i];
Response.write(' Yes<br>');
}
else { Response.write(' No<br>'); }
}
}
} else { // <= This part works fine
var min = arr[0];
for (var i in arr) {
if (arr[i] < min) {
min = arr[i];
}
}
}
}
################ THE RESULT:
################
156 < 156 ? No
321 < 156 ? No
67 < 156 ? No
275 < 156 ? No
252 < 156 ? No
56 < 156 ? No
23 < 156 ? No
300 < 156 ? No
400 < 156 ? No
290 < 156 ? No
321 < 156 ? No
312 < 156 ? No
343 < 156 ? No
210 < 156 ? No
234 < 156 ? No
390 < 156 ? No
332 < 156 ? No
190 < 156 ? No
143 < 156 ? Yes
230 < 143 ? No
################
For example, take this two statements:
result1 = 5 + 2; // Result is 7
result2 = 'foo' + 'bar'; // Result is 'foobar'
The numbers are added, but the strings are concatenated.
Now consider:
result3 = '$' + 5.25; // Result is '$5.25'
Here, JavaScript performs automatic data conversion. Because '$' is a string, it has to convert the number 5.25 into a string and concatenate it.
Compare this with:
result4 = '6' * 2; // Result is 12
Because * doesn't work on strings (you can't multiply a string!), JavaScript converts the string '6' into a number and multiplies it by two.
But what about this?
result5 = '3' + 5; // Result is...?
Intuitively, you might think that the result would be 8, especially if '3' were a variable (result5=x+5). But in fact it's not; JavaScript converts 5 to a string and concatenates the two strings to produce the result '35', not 8.
This also happens with < and >. They can be used to compare numbers or strings. For example:
result6 = 5 < 2; // Result is false
result7 = 'aardvark' < 'zoo'; // Result is true
So consider this:
result8 = '11' < '2'; // Result is true!
If you look at your code, you'll find that you've assigned all your data as strings. Remove the quotation marks from around the numbers, and that should do the trick.
Just to make absolutely sure, though, you might want to force JavaScript to convert to the appropriate data type. There is no equivalent of type casting (as in Java or C++), but there is a very simple trick.
To convert strings to numbers, subtract zero:
result9 = '11' - 0; // Result is the number 11
And to convert numbers to strings, add the empty string:
result10 = 11 + ''; // Result is the string '11'
This exposes as a misconception the idea that JavaScript is "easier" than Java. There's a lot going on "behind the scenes" in JavaScript, and it can really mess up your scripts; in Java, you have total control.