↑
Main Page
function
The highlighted block of code contains an
if
statement testing which array has more items (if they are
equal, no changes are necessary). Both branches of the
if
statement do the same thing on different
arrays: The first adds zeroes to
aVersion2
, whereas the second adds zeroes to
aVersion1
. After this
point, both arrays have an equal number of digits.
The final step is to iterate through the arrays and compare the corresponding digits in each array:
function compareVersions(sVersion1, sVersion2) {
var aVersion1 = sVersion1.split(“.”);
var aVersion2 = sVersion2.split(“.”);
if (aVersion1.length > aVersion2.length) {
for (var i=0; i < aVersion1.length - aVersion2.length; i++) {
aVersion2.push(“0”);
}
} else if (aVersion1.length < aVersion2.length) {
for (var i=0; i < aVersion2.length - aVersion1.length; i++) {
aVersion1.push(“0”);
}
}
for (var i=0; i < aVersion1.length; i++) {
if (aVersion1[i] < aVersion2[i]) {
return -1;
} else if (aVersion1[i] > aVersion2[i]) {
return 1;
}
}
return 0;
}
In this section, a
for
loop is used to compare the arrays. If a digit in
aVersion1
is less than the corre-
sponding digit in
aVersion2
, the function automatically exits and returns –1. Likewise, if the digit in
aVersion1
is greater than the one from
aVersion2
, the function exits and returns 1. If all digits are
tested and no value has been returned, the function returns 0, meaning that the two versions are equal.
This function is used like this:
alert(compareVersions(“0.9.2”, “0.9”)); //returns 1
alert(compareVersions(“1.13.2”, “1.14”)); //returns –1
alert(compareVersions(“5.5”, “5.5”)); //returns 0
The first line returns 1 because 0.9.2 is greater than 0.9; the second line returns –1, because 1.13.2 is less
than 1.14; the third line returns 0 because the two versions are equal. This function is used extensively in
this chapter.
236
Chapter 8
11_579088 ch08.qxd 3/28/05 11:38 AM Page 236
Free JavaScript Editor
Ajax Editor
©
→